写日志C#程序

/// <summary>
    ///把错误日志写入文件
    /// </summary>
    /// <param name="context">日志内容</param>
    public void wirteFile(string context)
    {
        System.IO.StreamWriter strwriter = null;
        try
        {
            lock (this)
            {
                string filePath = ConfigurationManager.AppSettings["logpath"];
                string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "_log.txt";

                //如果目录不存在则创建
                if (!System.IO.Directory.Exists(filePath))
                {
                    System.IO.Directory.CreateDirectory(filePath);
                }

                //定义文件信息对象       
                FileInfo finfo = new FileInfo(filePath + fileName);

                //创建只写文件流       
                using (FileStream fs = finfo.OpenWrite())
                {
                    //根据上面创建的文件流创建写数据流           
                    strwriter = new StreamWriter(fs);

                    //设置写数据流的起始位置为文件流的开头           
                    strwriter.BaseStream.Seek(0, SeekOrigin.End);

                    //写入
                    strwriter.WriteLine(DateTime.Now.ToString("HH:mm:ss >>") + context);

                    ////清空缓冲区内容,并把缓冲区内容写入基础流           
                    strwriter.Flush();
                    //关闭写数据流           
                    strwriter.Close();
                }
            }
        }
        finally
        {
            if (strwriter != null)
            {
                strwriter.Dispose();
            }
        }
    }

posted on 2009-09-11 11:56  Winlone囧  阅读(14)  评论(0编辑  收藏

导航