/// <summary>
/// 输出指定信息到文本文件
/// </summary>
/// <param name="msg">输出信息</param>
public void WriteMessage(string msg, string userName)
{
try
{ string mainPath = "F:\\log\\";//日志文件路径&配置到Config文件中直接获取
string path = mainPath;
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(, SeekOrigin.End);
//sw.WriteLine("------------------------------------------------------------------------ Info Start ");
sw.WriteLine("操作时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.WriteLine("操作人:" + userName);
sw.WriteLine("Message:{0}\n", msg, DateTime.Now);
sw.WriteLine("------------------------------------------------------------------------ ");
Console.WriteLine("\n");
sw.Flush();
}
} //当前月份
int totalmonth = int.Parse(month);
int totalyear = int.Parse(year);
int tmonth = ;//保留日志时长,月度单位
DateTime date;
string datestring = ""; DirectoryInfo dyInfo = new DirectoryInfo(mainPath);
//删除历史数据,保留6个月日志
if (totalmonth < tmonth)
{
//删除前一年totalmonth+6月份之前的数据
datestring = (totalyear - ).ToString() + "-" + (totalmonth + tmonth).ToString().PadLeft(, '') + "-" + "01 00:00:00"; }
else
{
//删除当年6个月前的数据
datestring = (totalyear).ToString() + "-" + (totalmonth - tmonth).ToString().PadLeft(, '') + "-" + "01 00:00:00";
}
date = Convert.ToDateTime(datestring);
//获取文件夹下所有的文件
foreach (FileInfo feInfo in dyInfo.GetFiles())
{
//判断文件日期是否小于今天,是则删除
if (feInfo.CreationTime < date)
feInfo.Delete();
}
}
catch (Exception)
{
}
}