讀寫文件之日誌文件

咱們在寫軟件的時候,常常要記錄一些登錄信息、刪除信息之類,便於往後查詢。我簡單寫了一個針對日誌文件的類,能夠經過此類能夠自定義日誌文件名稱,當日志達到規定大小時,自動備份,路徑能夠自行定義具體以下: 命名空間:javascript

using System; using System.Web; using System.IO; using System.Text;java

具體實現: public class LogFile { protected string LogfileName; // 文件名稱 protected string LogPath = "../upedFile"; // 文件路徑 protected int LogMaxContent = 2048; // 文件大小 protected string InputContent; // 具體內容ui

public LogFile() {日誌

}code

public LogFile(string StrLogfileName,string StrInputContent,string StrLogPath) { LogfileName = StrLogfileName; InputContent = StrInputContent; LogPath = StrLogPath;ip

}string

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);it

string PathNameMove = PathName.Substring(0,PathName.LastIndexOf("\"))+"\" + DateTime.Now.ToString("yyyyMMddhhmm") + LogfileName;ast

if( Finfo.Exists && Finfo.Length > LogMaxContent ) // 若是超出,重名名 { Finfo.CopyTo(PathNameMove); Finfo.Delete(); }class

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>"); }

}

相關文章
相關標籤/搜索