Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何替换文件中已存在的数据并写入新数据_C#_Winforms_Datagridview - Fatal编程技术网

C# 如何替换文件中已存在的数据并写入新数据

C# 如何替换文件中已存在的数据并写入新数据,c#,winforms,datagridview,C#,Winforms,Datagridview,您好,我编写了一个代码,将最后一行datagrid视图写入一个文件,如下所示 private void Save_Click(object sender, EventArgs e) { if (dataGridView1.Rows.Count > 0) { List<string> lstContent = new List<string>(); foreach (Da

您好,我编写了一个代码,将最后一行datagrid视图写入一个文件,如下所示

    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);
                    }
                }
            }

        }


    }
private void保存\u单击(对象发送方,事件参数e)
{
如果(dataGridView1.Rows.Count>0)
{
List lstContent=新列表();
foreach(dataGridView1.Rows中的DataGridViewRow行)
{
如果((字符串)行。单元格[0]。值==“FileControl”)
{
lstContent.Add((字符串)row.Cells[1].Value);
string mydata=string.Join(“,”,lstContent.ToArray());
使用(StreamWriter sw=新StreamWriter(Append.FileName,true))
{
sw.WriteLine();
软件写入(mydata);
}
}
}
}
}

但如果我多次单击save,这就是多次写入该行,我需要的是,如果文件中已经存在该行,我必须用新行替换该行。请提供任何帮助

您的StreamWriter正在显式使用append=true的文件。如果每次都要覆盖该文件,请将构造函数的第二个参数更改为false。文档是。引述:

附加

类型:System.Boolean

决定 是否将数据附加到 文件如果文件存在,并且append为 false,文件被覆盖。如果 文件存在且append为true,则 数据将附加到文件中。 否则,将创建一个新文件

修订守则:

  using (StreamWriter sw = new StreamWriter(Append.FileName, false))
  {
      sw.WriteLine();
      sw.Write(mydata);
  }
替换文件中的给定行比覆盖整个文件要困难得多-这段代码无法完成
StreamWriter
不适合这样做,您需要随机访问,并且能够用不同长度的不同数据段替换一个数据段(行),这是一项昂贵的磁盘操作


您可能希望将文件作为
String
s的容器保存在内存中,并在容器中执行所需的行替换,然后使用-将文件写入磁盘,如果文件不是太大。

如果我将其设置为false,则无法在文本文件中找到第一行,只有最后一行是displayed@Dorababu-请参阅编辑-如果没有更多工作和重组,您将无法执行此操作-StreamWriter不是合适的类。