2013-03-13 136 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来确保打开和关闭文件选项将被照顾。