C# 生成log文件

public void WriteLog(string strLog)
{
  string sFilePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
  string sFileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
  sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径
  if (!Directory.Exists(sFilePath))//验证路径是否存在
  {
    Directory.CreateDirectory(sFilePath);
    //不存在则创建
  }
  FileStream fs;
  StreamWriter sw;
  if (File.Exists(sFileName))
  //验证文件是否存在,有则追加,无则创建
  {
    fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
  }
  else
  {
    fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
  }
  sw = new StreamWriter(fs);
  sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " --- " + strLog);
  sw.Close();
  fs.Close();
}

 

posted @ 2020-05-12 19:23  朱志  阅读(1941)  评论(0编辑  收藏  举报