附加在C#中的文本文件中

我试图从C#写一个txt文件,如下所示:

File.WriteAllText("important.txt", Convert.ToString(c)); File.WriteAllLines("important.txt", (from r in rec select r.name + " " + r.num1 + " " + r.num2 + " " + r.mult + " " + r.rel).ToArray()); 

但是第二个File.WriteAllLines会覆盖文件中的第一个条目。 有什么建议我如何追加数据?

您应该使用File.AppendAllLines ,例如:

 File.WriteAllText("important.txt", Convert.ToString(c)); File.AppendAllLines("important.txt", (from r in rec select r.name + " " + r.num1 + " " + r.num2 + " " + r.mult + " " + r.rel).ToArray()); 

System.IO.File.AppendAllLines存在于.NET framework 4.0中。 如果您使用的是.NET Framework 3.5,则有AppenAllText方法,您可以像这样编写代码:

 File.WriteAllText("important.txt", Convert.ToString(c)); File.AppendAllText("important.txt", string.Join(Environment.NewLine, (from r in rec select r.name + " " + r.num1 + " " + r.num2 + " " + r.mult + " " + r.rel).ToArray())); 

试试这个

  File.WriteAllLines("important.txt", Convert.ToString(c) + (from r in rec select r.name + " " + r.num1 + " " + r.num2 + " " + r.mult + " " + r.rel).ToArray());