日志记录到Txt

        private static StreamWriter streamWriter; //写文件
        /// <summary>
        /// 写入txt 生成日志文件
        /// </summary>
        /// <param name="message">写入日志的内容</param>
        public void WriteLogTxt(string message)
        {
            try
            {
                string directPath = @"D:\工作文件\操作文件夹"; //获取文件夹路径
                if (!Directory.Exists(directPath)) //判断文件夹是否存在,如果不存在则创建
                {
                    Directory.CreateDirectory(directPath);
                }
                directPath += string.Format(@"\{0}", "处理报告日志");
                if (streamWriter == null)
                {
                    streamWriter = !File.Exists(directPath) ? File.CreateText(directPath) : File.AppendText(directPath); //判断文件是否存在 如果不存在则创建 如果存在则添加
                }
                streamWriter.WriteLine("***********************************************************************");
                streamWriter.WriteLine("处理时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                if (message != null)
                {
                    streamWriter.WriteLine("处理内容:" + message);
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Flush();
                    streamWriter.Dispose();
                    streamWriter = null;
                }
            }
        }

  

     public void btn_Click(object sender, EventArgs e)
        {
            try
            {
                //正确操作
            }
            catch (Exception ex)
            {
                WriteLogTxt(ex.ToString());
                throw ex;
            }
        }

  最近做的东西中用到写入txt文件中内容,出自:http://www.cnblogs.com/xinchun/p/4367169.html   自己用完后整理一下,加深印象,以后用到可以看。

posted on 2017-08-25 15:13  Amberlyn  阅读(159)  评论(0编辑  收藏  举报