C#程式Log的保存

  噹噹噹噹,我又來啦,这次终于可以插入代码了~這一次關於Log的保存的,將相關運行訊息保存到以日期命名的txt檔內。

  1. 在執行目錄下新建Log文件夾。

   string filePath = System.AppDomain.CurrentDomain.BaseDirectory + " Log ";   //AppDomain.CurrentDomain.BaseDirectory為獲取程式的基目錄,基目錄後加上Log為Log路徑

  if ( ! Directory.Exists( filePath ) )   Directory.CreateDirectory ( filePath ) ;   //如果路徑不存在,則創建此路徑(即程式基目錄下沒有Log這個文件夾時創建Log文件夾)

  2. 在Log文件夾下建立以日期命名的txt檔,並且將相應信息寫入此txt檔。 

  string logPath = filePath + " \\ " +DateTime.Now.ToString ( " yyyy-MM-dd " )  + " .txt " ;   //txt檔路徑,在Log文件夾路徑後加上\xxxx-xx-xx.txt,第一個 “ \ ” 為轉義符。

  try

  {

    using ( StreamWriter sw = File.AppendText ( logPath )   //打开文件并准备写信息

    {

      sw.WriteLine ( DateTime.Now.ToString ( " HH:mm:ss " ) + " 需要保存的運行信息 " ) ;   //写入當前時間+相应信息

    }

  }

  catch ( Exception ex )   //寫log過程中出現異常

  {

    MessageBox.Show ( DateTime.Now.ToString ( " HH:mm:ss " ) + " 寫日誌失敗 " ,  " 錯誤提示 "  ) ;   //跳出MessageBox,顯示為錯誤提示,並指明寫日誌失敗

  }

  3. 定期清除:log檔每滿7天就將7天前的log檔清除。

string[] files=Directory.GetFiles(filePath, "*.txt");  //Log文件夹下的所有txt文件信息数组
foreach(var file in files)  //每个txt文件
{
    FileInfo fi=new FileInfo(file);  //new一个FileInfo对象fi
    if((DateTime.Now-fi.CreatTime).TotalDays>7) fi.Delete();  //如果现在时间减去txt档的创建时间大于7,将此txt档删除
    else break;
}

  简单的运行信息保存log的程式如上,方法不仅限于这一种,大家可以在网上查找,多试试。

    

猜你喜欢

转载自www.cnblogs.com/kigila/p/11777937.html
今日推荐