开发者

How to replace a data from a file if already exists and write a new data

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开发者_JS百科)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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜