写日志文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication42
{ //某个项目,需要写日志到系统目录下的siyktLog,日志名称是以当天时间为文件名,写日志时,准确地写入当时时间日期,精确到毫秒
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.Now;
//测试siyktLog文件夹
string sysPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
string siyktLogPath=sysPath+"";
if (!Directory.Exists(siyktLogPath))
{
Directory.CreateDirectory(siyktLogPath);
}
//测试当日日志文件
string logfileName =siyktLogPath +"\\"+ dt.ToShortDateString() +".log";
if (!File.Exists(logfileName))
{
FileStream tempFS = File.Create(logfileName);
tempFS.Close(); //要记得及时关闭,否则下面会报错
}
//测试文件写入
FileStream fs = new FileStream(logfileName, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
string strTime=string.Format("{0:yyyy-MM-dd HH:mm:ss.ffff:}", dt);
sw.Write(strTime);
sw.WriteLine("第一次测试");
sw.Close();
Console.ReadKey();
}
}
}