使用WriteAllLines附加到文本文件
我使用以下代码写入文本文件。 我的问题是,每次执行以下代码时,它都会清空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);
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内容)
有三个function..File.AppendAllLine,FileAppendAllText和FileAppendtext ..你可以尝试像你一样…
在上述所有情况中,我更喜欢使用以确保打开和关闭文件选项。