码迷,mamicode.com
首页 > Windows程序 > 详细

C#保存日志文件到txt中,可追加保存

时间:2019-03-04 17:23:55      阅读:447      评论:0      收藏:0      [点我收藏+]

标签:pen   origin   年度   create   public   创建文件   直接   文本文件   image   

/// <summary>
/// 输出指定信息到文本文件
/// </summary>
/// <param name="msg">输出信息</param>
public void WriteMessage(string msg)
{
string path = "F:\\log\\";//日志文件路径&配置到Config文件中直接获取
string filename = DateTime.Now.ToString("yyyyMMdd") + ".txt";//文件名
string year = DateTime.Now.ToString("yyyy");//年
string month = DateTime.Now.ToString("MM");//月

//判断log文件路径是否存在,不存在则创建文件夹
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}

path += year + "\\";
//判断年度文件夹是否存在,不存在则创建文件夹
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}

path += month + "\\";
//判断月度文件夹是否存在,不存在则创建文件夹
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}

//拼接完整文件路径
path += filename;
if (!File.Exists(path))
{
//文件不存在,新建文件
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
sw.Close();
}

using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.BaseStream.Seek(0, SeekOrigin.End);
//sw.WriteLine("------------------------------------------------------------------------ Info Start ");
sw.WriteLine("操作时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.WriteLine("Message:{0}\n", msg, DateTime.Now);
sw.WriteLine("------------------------------------------------------------------------ ");
Console.WriteLine("\n");
sw.Flush();
}
}
}

技术图片

 

C#保存日志文件到txt中,可追加保存

标签:pen   origin   年度   create   public   创建文件   直接   文本文件   image   

原文地址:https://www.cnblogs.com/teenagermostr/p/10471680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!