Asp.net怎样将一个数据写入到.txt文本文件

2025-05-09 17:47:06

1、对于.net写入txt的操作,实际过程就是一个文件写入的过程。我们会使用到Directory、FileInfo等等一些基本的文件操作类。下面,小编以实例来介绍如何将数据写入到txt中。

2、编写写入txt的方法,首选,要判断txt所在的文件夹是否存在,以防程序读取不到目录出现异常,如果不存在,我们通过程序来创建文件夹。string dir = System.Web.HttpContext.Current.Server.MapPath("~/log"); if (Directory.Exists(dir) == false) { Directory.CreateDirectory(dir); }

Asp.net怎样将一个数据写入到.txt文本文件

4、我们訇咀喃谆将上述代码放到一个方法中去,主要是为了方便调用,可以快速将要写入的内容写入到txt中。public static void CreateWebLog(string logStr) { try { string dir = System.Web.HttpContext.Current.Server.MapPath("~/log"); if (Directory.Exists(dir) == false) { Directory.CreateDirectory(dir); } string strFilePath = System.Web.HttpContext.Current.Server.MapPath("~/log/log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt"); FileInfo logFile = new FileInfo(strFilePath); System.IO.FileStream fs; if (logFile.Exists) { fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append); } else { fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Create); } System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default); sw.WriteLine("---------------------------------------------------------------------------------------"); sw.WriteLine("-----------------------------" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "---------------------------------------"); sw.WriteLine("---------------------------------------------------------------------------------------"); sw.WriteLine(logStr); sw.Close(); fs.Close(); } catch (Exception) { } }

Asp.net怎样将一个数据写入到.txt文本文件Asp.net怎样将一个数据写入到.txt文本文件
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢