1.创建日志文件,按照年、月进行文件分类,年月日作为文本名称
private void newFile()
{
if (!Directory.Exists(Application.StartupPath + "\\Datelog\\"+ DateTime.Now.Year.ToString() +"年\\"+ DateTime.Now.Month.ToString() + "月"))
{
Directory.CreateDirectory(Application.StartupPath + "\\Datelog\\" + DateTime.Now.Year.ToString() + "年\\" + DateTime.Now.Month.ToString()+"月");
Console.WriteLine(Application.StartupPath + "\\Datelog\\" + DateTime.Now.Year.ToString() + "年\\" + DateTime.Now.Month.ToString() + "月");
} //在程序运行的目录下,创建Datelog目录用于存放日志
if (!File.Exists(Application.StartupPath + "\\Datelog\\" + DateTime.Now.Year.ToString() + "年\\" + DateTime.Now.Month.ToString()+"月\\" + DateTime.Now.ToString("yyyy.MM.dd") + ".txt"))
{
FileStream fs1 = new FileStream(Application.StartupPath + "\\Datelog\\" + DateTime.Now.Year.ToString() + "年\\" + DateTime.Now.Month.ToString() + "月\\" + DateTime.Now.ToString("yyyy.MM.dd") + ".txt", FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs1);
fs1.Close();
}//创建日志文件
else
{
FileStream fs = new FileStream(Application.StartupPath + "\\Datelog\\" + DateTime.Now.Year.ToString() + "年\\" + DateTime.Now.Month.ToString() + "月\\" + DateTime.Now.ToString("yyyy.MM.dd") + ".txt", FileMode.Open, FileAccess.Write);
fs.Close();
}//打开日志文件
}
2.写入内容
string rz = DateTime.Now.ToString("HH:mm:ss") + ":" + " 更新数据表 TackingList中"+" 窗口时间为:" + endtime + "的数据状态" +"\n";
StreamWriter sw = new StreamWriter(Application.StartupPath + "\\Datelog\\" + DateTime.Now.Year.ToString() + "年\\" + DateTime.Now.Month.ToString() + "月\\" + DateTime.Now.ToString("yyyy.MM.dd") + ".txt", true);
sw.WriteLine(rz);
sw.Close();