2012-03-31 174 views
2

我想写从C#一个txt文件,如下所示:追加在C#中的文本文件

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

试试这个

File.WriteAllLines("important.txt", Convert.ToString(c) + (from r in rec 
        select r.name + " " + r.num1 + " " + r.num2 + " " + r.mult + " " + r.rel).ToArray()); 
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())); 
+0

我得到了错误systemIO。文件不包含AppendAllLines的定义。 – 2012-03-31 23:37:34

+0

方法System.IO.File.AppendAllLines肯定存在。请检查你是否拼写错误。 – 2012-04-01 01:34:37

+0

AppendAllLines来自.NET 4.0。如果您使用的是旧版本的.NET框架,请参阅我的更新回答。 – 2012-04-01 01:40:49