1. 程式人生 > >日誌記錄到Txt

日誌記錄到Txt

*** event 獲取 pub text csharp cli final 文件夾

        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 自己用完後整理一下,加深印象,以後用到可以看。

日誌記錄到Txt