读写文件之日志文件

咱们在写软件的时候,常常要记录一些登录信息、删除信息之类,便于往后查询。我简单写了一个针对日志文件的类,能够经过此类能够自定义日志文件名称,当日志达到规定大小时,自动备份,路径能够自行定义具体以下: 命名空间: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>"); }

}

相关文章
相关标签/搜索