当前位置: 首页 > 编程语言 > C#

使用WriteAllLines附加到文本文件分享

时间:2023-04-10 23:48:53 C#

C#学习教程:使用WriteAllLines附加到文本文件我的问题是每次执行以下代码时,它都会清空txt文件并创建一个新文件。有没有办法附加到这个txt文件?string[]lines={DateTime.Now.Date.ToShortDateString(),DateTime.Now.TimeOfDay.ToString(),消息,类型,模块};System.IO.File.WriteAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"),行);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"),行);使用File.AppendAllLines。它应该做System.IO.File.AppendAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"),lines);你可以使用StreamWriter;如果文件存在,您可以覆盖或追加。如果文件不存在,此构造函数将创建一个新文件。string[]lines={DateTime.Now.Date.ToShortDateString(),DateTime.Now.TimeOfDay.ToString(),消息,类型,模块};使用(StreamWriterstreamWriter=newStreamWriter(HttpContext.Current.Server.MapPath("~/logger.txt"),true)){streamWriter.WriteLine(lines);}做这样的事情:string[]lines={DateTime.Now.Date.ToShortDateString(),DateTime.Now.TimeOfDay.ToString(),message,type,module};如果(!File.Exists(HttpContext.Current.Server.MapPath("~/logger.txt"))){System.IO.File.WriteAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"),行);}else{System.IO.File.AppendAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"),行);因此,如果文件不存在,它将创建并写入文件,如果存在则追加到文件中。使用publicstaticvoidAppendAllLines(Stringpath,IEnumerablecontent)有三个函数..File.AppendAllLine,FileAppendAllText和FileAppendtext..你可以像你一样尝试......在上述所有情况下,我更喜欢使用来确保文件是打开和关闭选项。以上就是C#学习教程:使用WriteAllLines将所有内容附加到文本文件中进行分享。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权请点击右侧联系管理员删除。如需转载请注明出处: