C# 写日志方法

1.Write方法是写日志主要方法。

2.DeleteLog方法是删除指定日期之前生成的日志。

public static void Write(string Msg)
        {
            string strPath;
            DateTime dt = DateTime.Now;
            try
            {
                strPath =AppDomain.CurrentDomain.BaseDirectory + "\\Log";
                if (Directory.Exists(strPath) == false)
                {
                    Directory.CreateDirectory(strPath);
                }

                DeleteLog(strPath);

                strPath = strPath + "\\" + dt.ToString("yyyyMMdd") + ".txt";
                StreamWriter FileWriter = new StreamWriter(strPath, true);
                FileWriter.WriteLine(dt.ToString("HH:mm:ss")  + Msg);
                FileWriter.Close();
            }
            catch (Exception ex)
            {
                string str = ex.Message.ToString();
            }
        }
        public static void DeleteLog(string sLogPath)
        {
            //string strFolderPath = @"E:\Zhao\我的代码\f福建中医药大学附属人民医院\定制化服务\bin\Debug\logs";

            DirectoryInfo dyInfo = new DirectoryInfo(sLogPath);
            //获取文件夹下所有的文件
            foreach (FileInfo feInfo in dyInfo.GetFiles())
            {
                //判断文件日期是否小于指定日期,是则删除
                if (feInfo.CreationTime < DateTime.Now.AddDays(-15))
                    feInfo.Delete();
            }
        }

PS:附详细图片一张:

C# 写日志方法_第1张图片

你可能感兴趣的:(C# 写日志方法)