天天看點

VS C#儲存日志檔案到txt中,可追加儲存,定時删除最後一次操作半年前日志檔案

/// <summary>
        /// 輸出指定資訊到文本檔案
        /// </summary>
        /// <param name="msg">輸出資訊</param>
        public void WriteMessage(string msg, string userName)
        {
            try
            {

                string mainPath = "F:\\log\\";//日志檔案路徑&配置到Config檔案中直接擷取
                string path = mainPath;
                string filename = DateTime.Now.ToString("yyyyMMdd") + ".txt";//檔案名
                string year = DateTime.Now.ToString("yyyy");//年
                string month = DateTime.Now.ToString("MM");//月

                //判斷log檔案路徑是否存在,不存在則建立檔案夾
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);//不存在就建立目錄
                }

                path += year + "\\";
                //判斷年度檔案夾是否存在,不存在則建立檔案夾
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);//不存在就建立目錄
                }

                path += month + "\\";
                //判斷月度檔案夾是否存在,不存在則建立檔案夾
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);//不存在就建立目錄
                }

                //拼接完整檔案路徑
                path += filename;
                if (!File.Exists(path))
                {
                    //檔案不存在,建立檔案
                    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Close();
                }

                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.BaseStream.Seek(0, SeekOrigin.End);
                        //sw.WriteLine("------------------------------------------------------------------------ Info Start ");
                        sw.WriteLine("操作時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        sw.WriteLine("操作人:" + userName);
                        sw.WriteLine("Message:{0}\n", msg, DateTime.Now);
                        sw.WriteLine("------------------------------------------------------------------------ ");
                        Console.WriteLine("\n");
                        sw.Flush();
                    }
                }

                //目前月份
                int totalmonth = int.Parse(month);
                int totalyear = int.Parse(year);
                int tmonth = 6;//保留日志時長,月度機關
                DateTime date;
                string datestring = "";

                DirectoryInfo dyInfo = new DirectoryInfo(mainPath);
                //删除曆史資料,保留6個月日志
                if (totalmonth < tmonth)
                {
                    //删除前一年totalmonth+6月份之前的資料
                    datestring = (totalyear - 1).ToString() + "-" + (totalmonth + tmonth).ToString().PadLeft(2, '0') + "-" + "01 00:00:00";

                }
                else
                {
                    //删除當年6個月前的資料
                    datestring = (totalyear).ToString() + "-" + (totalmonth - tmonth).ToString().PadLeft(2, '0') + "-" + "01 00:00:00";
                }
                date = Convert.ToDateTime(datestring);
                //擷取檔案夾下所有的檔案
                foreach (FileInfo feInfo in dyInfo.GetFiles())
                {
                    //判斷檔案日期是否小于今天,是則删除
                    if (feInfo.CreationTime < date)
                        feInfo.Delete();
                }
            }
            catch (Exception)
            {
            }
        }