C#保存日志文件到txt中,可追加保存,定时删除最后一次操作半年前日志文件
1 /// <summary> 2 /// 输出指定信息到文本文件 3 /// </summary> 4 /// <param name="msg">输出信息</param> 5 public void WriteMessage(string msg, string userName) 6 { 7 try 8 { 9 10 string mainPath = "F:\\log\\";//日志文件路径&配置到Config文件中直接获取 11 string path = mainPath; 12 string filename = DateTime.Now.ToString("yyyyMMdd") + ".txt";//文件名 13 string year = DateTime.Now.ToString("yyyy");//年 14 string month = DateTime.Now.ToString("MM");//月 15 16 //判断log文件路径是否存在,不存在则创建文件夹 17 if (!System.IO.Directory.Exists(path)) 18 { 19 System.IO.Directory.CreateDirectory(path);//不存在就创建目录 20 } 21 22 path += year + "\\"; 23 //判断年度文件夹是否存在,不存在则创建文件夹 24 if (!System.IO.Directory.Exists(path)) 25 { 26 System.IO.Directory.CreateDirectory(path);//不存在就创建目录 27 } 28 29 path += month + "\\"; 30 //判断月度文件夹是否存在,不存在则创建文件夹 31 if (!System.IO.Directory.Exists(path)) 32 { 33 System.IO.Directory.CreateDirectory(path);//不存在就创建目录 34 } 35 36 //拼接完整文件路径 37 path += filename; 38 if (!File.Exists(path)) 39 { 40 //文件不存在,新建文件 41 FileStream fs = new FileStream(path, FileMode.OpenOrCreate); 42 StreamWriter sw = new StreamWriter(fs); 43 sw.Close(); 44 } 45 46 using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) 47 { 48 using (StreamWriter sw = new StreamWriter(fs)) 49 { 50 sw.BaseStream.Seek(0, SeekOrigin.End); 51 //sw.WriteLine("------------------------------------------------------------------------ Info Start "); 52 sw.WriteLine("操作时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 53 sw.WriteLine("操作人:" + userName); 54 sw.WriteLine("Message:{0}\n", msg, DateTime.Now); 55 sw.WriteLine("------------------------------------------------------------------------ "); 56 Console.WriteLine("\n"); 57 sw.Flush(); 58 } 59 } 60 61 //当前月份 62 int totalmonth = int.Parse(month); 63 int totalyear = int.Parse(year); 64 int tmonth = 6;//保留日志时长,月度单位 65 DateTime date; 66 string datestring = ""; 67 68 DirectoryInfo dyInfo = new DirectoryInfo(mainPath); 69 //删除历史数据,保留6个月日志 70 if (totalmonth < tmonth) 71 { 72 //删除前一年totalmonth+6月份之前的数据 73 datestring = (totalyear - 1).ToString() + "-" + (totalmonth + tmonth).ToString().PadLeft(2, '0') + "-" + "01 00:00:00"; 74 75 } 76 else 77 { 78 //删除当年6个月前的数据 79 datestring = (totalyear).ToString() + "-" + (totalmonth - tmonth).ToString().PadLeft(2, '0') + "-" + "01 00:00:00"; 80 } 81 date = Convert.ToDateTime(datestring); 82 //获取文件夹下所有的文件 83 foreach (FileInfo feInfo in dyInfo.GetFiles()) 84 { 85 //判断文件日期是否小于今天,是则删除 86 if (feInfo.CreationTime < date) 87 feInfo.Delete(); 88 } 89 } 90 catch (Exception) 91 { 92 } 93 }