使用WriteAllLines追加到文本文件

本文关键字:文本 文件 追加 WriteAllLines 使用 | 更新日期: 2023-09-27 18:03:51

我使用以下代码在文本文件中编写。我的问题是,每次执行以下代码时,它都会清空txt文件并创建一个新文件。是否有一种方法来附加到这个txt文件?

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

使用WriteAllLines追加到文本文件

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);

使用File.AppendAllLines。应该可以了

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

你可以使用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);
}

这样做:

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);
          }

如果文件不存在,它将创建并写入文件如果文件存在,它将追加到文件

使用

public static void AppendAllLines字符串路径,IEnumerable内容)

三个功能可用…AppendAllLine,FileAppendAllText和FileAppendtext..你可以尝试你喜欢的…

在上述所有情况下,我更喜欢使用using来确保打开和关闭文件选项会被注意到