我們在寫軟件的時候,經常要記錄一些登陸信息、刪除信息之類,便於日後查詢。我簡單寫了一個針對日志文件的類,可以通過此類可以自定義日志文件名稱,當日志達到規定大小時,自動備份,路徑可以自行定義具體如下:
命名空間:
using System;
using System.Web;
using System.IO;
using System.Text;
具體實現:
public class LogFile
{
protected string LogfileName; // 文件名稱
protected string LogPath = "../upedFile"; // 文件路徑
protected int LogMaxContent = 2048; // 文件大小
protected string InputContent; // 具體內容
public LogFile()
{
}
public LogFile(string StrLogfileName,string StrInputContent,string StrLogPath)
{
LogfileName = StrLogfileName;
InputContent = StrInputContent;
LogPath = StrLogPath;
}
public void LogWrite()
{
// string PathName = System.Web.HttpContext.Current.Server.MapPath(LogPath) + LogfileName;
string PathName = System.Web.HttpContext.Current.Server.MapPath(LogPath) + "\\" + LogfileName;
FileInfo Finfo = new FileInfo(PathName);
string PathNameMove = PathName.Substring(0,PathName.LastIndexOf("\\"))+"\\" + DateTime.Now.ToString("yyyyMMddhhmm") + LogfileName;
if( Finfo.Exists && Finfo.Length > LogMaxContent ) // 如果超出,重名名
{
Finfo.CopyTo(PathNameMove);
Finfo.Delete();
}
try
{
using(FileStream Fs = Finfo.OpenWrite())
{
StreamWriter Sw = new StreamWriter(Fs);
Sw.BaseStream.Seek(0, SeekOrigin.End); //設置寫數據流的起始位置為文件流的末尾
StringBuilder StrInput = new StringBuilder(); // 記錄寫入的內容
StrInput.Append("\r\n Log Entry : ");
StrInput.Append(DateTime.Now.ToString());
StrInput.Append("\r\n");
StrInput.Append(InputContent + "\r\n");
StrInput.Append("------------------------------------\n");
Sw.Write(StrInput);
Sw.Flush();
Sw.Close();
}
}
catch
{
System.Web.HttpContext.Current.Response.Write("<script language=Javascript>alert(''日志創建失敗'')</script>");
}
}