我正在尝试从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会覆盖文件中的第一个条目。有任何建议我如何追加数据?
答案 0 :(得分:7)
您应该使用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()));
答案 1 :(得分:0)
试试这个
File.WriteAllLines("important.txt", Convert.ToString(c) + (from r in rec
select r.name + " " + r.num1 + " " + r.num2 + " " + r.mult + " " + r.rel).ToArray());