废话很少说,直接上代码,关键代码都有注释,不理解的能够留言提出.spa
private static StreamWriter streamWriter; //写文件 //将错误信息写入文件中 public static void WriteError(string message) { try { //DateTime dt = new DateTime(); string directPath = ConfigurationManager.AppSettings["LogFilePath"].ToString().Trim(); //在得到文件夹路径 if (!Directory.Exists(directPath)) //判断文件夹是否存在,若是不存在则建立 { Directory.CreateDirectory(directPath); } directPath += string.Format(@"\{0}.log", DateTime.Now.ToString("yyyy-MM-dd")); if (streamWriter == null) { streamWriter = !File.Exists(directPath) ? File.CreateText(directPath) : File.AppendText(directPath); //判断文件是否存在若是不存在则建立,若是存在则添加。 } streamWriter.WriteLine("***********************************************************************"); streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss")); streamWriter.WriteLine("输出信息:错误信息"); if (message != null) { streamWriter.WriteLine("异常信息:\r\n" + message); } } finally { if (streamWriter != null) { streamWriter.Flush(); streamWriter.Dispose(); streamWriter = null; } } }
ok,今天的分享就到这里了,有疑问的欢迎留言!code