分享

日志记录代码

 悟静 2012-02-25
using System;
using System.IO;
  
public class Log
{
    public Log()
    {
        logName = "";
    }
    public Log(string prefilename)
    {
        logName = prefilename;
    }
   private  string path = System.AppDomain.CurrentDomain.BaseDirectory + "Result\\";
    public   void clearTextfile()
    {
  
        try
        {
            if (Directory.Exists(path))
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                FileInfo[] txtfiles = dir.GetFiles("*.txt");
                foreach (FileInfo f in txtfiles)
                {
                    File.Delete(f.FullName);
                }
            }
        }
        catch
        {
        }
    }
    public string logName{ get;set;}
    public   void WriteLog(string msg)
    {
        try
        {
             
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            string logfilename = path +logName+ ".txt";
  
            FileStream fs = null;
            if (File.Exists(logfilename)) //如果文件存在就追加日志记录 
            {
                fs = new FileStream(logfilename, FileMode.Append, FileAccess.Write);
            }
            else //如果不存在,就创建日志文件 
            {
                  
                fs = new FileStream(logfilename, FileMode.Create, FileAccess.Write);
            }
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(msg);
            sw.Flush();
            sw.Close();
            fs.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多