調試及發布程序時,經常需要將一些信息輸出保存,這裡寫了一個自己的日志記錄類,記錄信息更方便了。需要的話還可以進行更多的擴展,比如記錄異常信息等。
using System;
using System.IO;
namespace WindowsFormsApplication1
{
public static class LogerHelper
{
#region 創建日志
///-----------------------------------------------------------------------------
/// 創建錯誤日志 在c:\ErrorLog\
/// 記錄信息
///
///-----------------------------------------------------------------------------
public static void CreateLogTxt(string message)
{
string strPath; //文件的路徑
DateTime dt = DateTime.Now;
try
{
strPath = Directory.GetCurrentDirectory() + "\\Log"; //winform工程\bin\目錄下 創建日志文件夾
if(Directory.Exists(strPath)==false) //工程目錄下 Log目錄 '目錄是否存在,為true則沒有此目錄
{
Directory.CreateDirectory(strPath); //建立目錄 Directory為目錄對象
}
strPath = strPath + "\\" + dt.ToString("yyyy");
if(Directory.Exists(strPath) == false)
{
Directory.CreateDirectory(strPath);
}
strPath = strPath + "\\" + dt.Year.ToString() + "-" + dt.Month.ToString() + ".txt";
StreamWriter FileWriter= new StreamWriter(strPath, true); //創建日志文件
FileWriter.WriteLine("[" + dt.ToString("yyyy-MM-dd HH:mm:ss") + "] " + message);
FileWriter.Close(); //關閉StreamWriter對象
}
catch(Exception ex)
{
string str=ex.Message.ToString();
}
}
#endregion
}
}