在刚开始做程序员时很多东西都需要从网上查询,试N多种才可以找到符合自己的。
现在这个时间我想分享的就是创建文件。
/// <summary>
/// 写日常日志,每月一个日常日志文件
/// </summary>
/// <param name="filename">自定义文件名字</param>
/// <param name="message">日志内容</param>
public static void WriteCommonLog(string filename, string message)
{
try
{
if (message != "" && filename != "")
{
string filepath = System.Web.HttpContext.Current.Server.MapPath("~/framework/Log/");//Server.MapPath获得的路径都是服务器上的物理路径,也就是常说的绝对路径
if (!System.IO.Directory.Exists(filepath))
{
System.IO.Directory.CreateDirectory(filepath);
}
filepath += "log_" + DateTime.Now.Year + "." + DateTime.Now.Month + "." + filename + ".txt";
if (!System.IO.File.Exists(filepath))
{
using (System.IO.FileStream filestream = new System.IO.FileStream(filepath, System.IO.FileMode.Create))
{
filestream.Close();
}
}
try
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filepath, true))
{
sw.WriteLine(DateTime.Now);
sw.WriteLine(message);
sw.WriteLine("");
sw.Close();
}
}
catch { }
}
}
catch { }
}