2013-03-13 137 views
2

我正在使用以下代碼來寫入文本文件。我的問題是,每次執行下面的代碼它都會清空txt文件並創建一個新文件。有沒有辦法追加到這個txt文件?使用WriteAllLines附加到文本文件

string[] lines = {DateTime.Now.Date.ToShortDateString(),DateTime.Now.TimeOfDay.ToString(), message, type, module }; 
System.IO.File.WriteAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"), lines); 

回答

6

File.AppendAllLines應該可以幫助您:

string[] lines = {DateTime.Now.Date.ToShortDateString(),DateTime.Now.TimeOfDay.ToString(), message, type, module }; 
System.IO.File.AppendAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"), lines); 
+0

AppendAllText不接受字符串數組作爲第二個參數。正確的答案應該是下面使用AppendAllLines方法的答案之一。 – 2015-03-27 22:44:32

+0

只需注意,這不會清除文本文件中的現有項目。 – Kurkula 2017-02-10 20:11:35

5

使用File.AppendAllLines。應該這樣做

System.IO.File.AppendAllLines(
     HttpContext.Current.Server.MapPath("~/logger.txt"), 
     lines); 
+1

需要.NET Framework 4.0+ – 2014-01-11 21:15:47

2

做這樣的事情:

string[] lines = {DateTime.Now.Date.ToShortDateString(),DateTime.Now.TimeOfDay.ToString(), message, type, module }; 
      if (!File.Exists(HttpContext.Current.Server.MapPath("~/logger.txt"))) 
      { 
       System.IO.File.WriteAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"), lines); 
      } 
      else 
      { 
       System.IO.File.AppendAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"), lines); 
      } 

所以,如果文件不存在,它會創建和文件,如果寫文件存在它將附加在文件上。

+2

不需要。如果文件不存在,AppendAllLines將創建該文件。 – nunespascal 2013-03-13 07:28:12

+0

System.IO.File中沒有附加行 – user1292656 2013-03-13 07:31:05

+0

@ user1292656:請檢查網上AppendAllLines方法是否存在,並且您正在討論AppendLines,上帝知道它是什麼。 – Popeye 2013-03-13 08:58:25

0

三個功能都可以..File.AppendAllLine,FileAppendAllText和FileAppendtext..you可以嘗試爲u喜歡...

1

使用

公共靜態無效AppendAllLines( 路徑字符串, IEnumerable的內容 )

3

您可以使用StreamWriter;如果文件存在,它可以被覆蓋或附加到。如果該文件不存在,則此構造函數將創建一個新文件。

string[] lines = { DateTime.Now.Date.ToShortDateString(), DateTime.Now.TimeOfDay.ToString(), message, type, module }; 

using(StreamWriter streamWriter = new StreamWriter(HttpContext.Current.Server.MapPath("~/logger.txt"), true)) 
{ 
    streamWriter.WriteLine(lines); 
} 
0

在上述所有情況下,我更願意使用using來確保打開和關閉文件選項將被照顧。