private static int cnt = 1;
public static void Write(string Msg)
{
string strPath;
DateTime dt = DateTime.Now;
if (dt.Hour == 0)
cnt = 1;
try
{
strPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogCustomiZation");
if (!Directory.Exists(strPath))
{
Directory.CreateDirectory(strPath);
}
DeleteLog(strPath);
strPath = strPath + "\\" + dt.ToString("yyyyMMdd") + "-" + cnt + ".txt";
FileInfo file = new FileInfo(strPath);
if (file.Exists)
{
//大于10M,写入新文件
if (file.Length > 1024 * 1024 * 10)
{
//file.Delete();
strPath = strPath + "\\" + dt.ToString("yyyyMMdd") + "-" + ++cnt + ".txt";
}
}
using (StreamWriter fileWriter = new StreamWriter(strPath, true))
{
fileWriter.WriteLine(dt.ToString("HH:mm:ss ff") + Msg);
fileWriter.Close();
}
}
catch (Exception ex)
{
string str = ex.Message.ToString();
}
}
public static void DeleteLog(string sLogPath)
{
DirectoryInfo dyInfo = new DirectoryInfo(sLogPath);
//获取文件夹下所有的文件
foreach (FileInfo feInfo in dyInfo.GetFiles())
{
//判断文件日期是否小于指定日期,是则删除
if (feInfo.CreationTime < DateTime.Now.AddDays(-7))
feInfo.Delete();
}
}
c# 日志文件保留N天,可自定义天数
于 2022-05-18 16:55:40 首次发布