/// <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();
}
}
}
原文地址:https://www.cnblogs.com/teenagermostr/p/10471680.html