2012-03-31 124 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