附加到C#中的文本文件中
本文关键字:文件 文本 | 更新日期: 2023-09-27 18:29:41
我正试图从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());
.NET framework 4.0中存在System.IO.File.AppendAllLines。如果你使用的是.NET framework 3.5,有AppeallText方法,你可以这样写代码:
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());