views:

29

answers:

1

Hi all i write a code to write my last row of datagrid view to a file as follows

    private void Save_Click(object sender, EventArgs e)
    {
        if (dataGridView1.Rows.Count > 0)
        {
            List<string> lstContent = new List<string>();

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if ((string)row.Cells[0].Value == "FileControl")
                {
                    lstContent.Add((string)row.Cells[1].Value);

                    string mydata = string.Join(",", lstContent.ToArray());

                    using (StreamWriter sw = new StreamWriter(Append.FileName, true))
                    {
                        sw.WriteLine();
                        sw.Write(mydata);
                    }
                }
            }

        }


    }

But if i click multiple times on save this is writing that line multiple times what i need is if already that line exists in the file i have to replace that line with new line. Any help please

A: 

Your StreamWriter is explicitly using the file with append = true. Change the second parameter of the constructor to false if you want to overwrite the file each time. Docs are here. Quote:

append

Type: System.Boolean

Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.

Revised code:

  using (StreamWriter sw = new StreamWriter(Append.FileName, false))
  {
      sw.WriteLine();
      sw.Write(mydata);
  }

Replacing a given line in your file rather than just overwriting the whole file is a lot more difficult - this code is not going to get it done. StreamWriter is not great for this, you need random access and the ability to replace one data segment (line) by a different data segment of different length, which is an expensive operation on disk.

You might want to keep the files in memory as a container of Strings and do your required line replacement within the container, then write out the file to disk using File.WriteAllLines - that's if the file is not too big.

Steve Townsend
If i set it to false i am unable to find my first line in my text file only that last data row is displayed
Dorababu
@Dorababu - see edit - you are not going to be able to do this without more work and a restructure - StreamWriter is not the right class.
Steve Townsend
I already tried to explain this all....
leppie