欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现将日志写入文本文件的方法

程序员文章站 2022-10-26 07:58:33
本文实例讲述了c#实现将日志写入文本文件的方法。分享给大家供大家参考。具体如下: 这里传入的参数是 要写的内容 using system.io; public...

本文实例讲述了c#实现将日志写入文本文件的方法。分享给大家供大家参考。具体如下:

这里传入的参数是 要写的内容

using system.io;
public static void writelog(string strlog)
{
  string sfilepath="d:\\"+datetime.now.tostring("yyyymm");
  string sfilename = "rizhi" + datetime.now.tostring("dd") + ".log";
  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();    
}

希望本文所述对大家的c#程序设计有所帮助。