iT邦幫忙

0

[筆記]C#在指定目錄中寫Log文字檔

新增類別txtLog.cs

 public class txtLog
    {
        private static String logPath = "C:\\TEST\\log"; //Log目錄

       
        public  void WriteLog(String logMsg)
        {
            //檔案名稱 使用現在日期
            String logFileName = DateTime.Now.Year.ToString() + int.Parse(DateTime.Now.Month.ToString()).ToString("00") + int.Parse(DateTime.Now.Day.ToString()).ToString("00") + ".txt";
            
            //Log檔內的時間 使用現在時間
            String nowTime = int.Parse(DateTime.Now.Hour.ToString()).ToString("00") + ":" + int.Parse(DateTime.Now.Minute.ToString()).ToString("00") + ":" + int.Parse(DateTime.Now.Second.ToString()).ToString("00");

            if (!Directory.Exists(logPath))
            {
                //建立資料夾
                Directory.CreateDirectory(logPath);
            }

            if (!File.Exists(logPath + "\\" + logFileName))
            {
                //建立檔案
                File.Create(logPath + "\\" + logFileName).Close();
            }

            using (StreamWriter sw = File.AppendText(logPath + "\\" + logFileName))
            {
                //WriteLine為換行 
                sw.Write(nowTime + "---->");
                sw.WriteLine(logMsg);
                sw.WriteLine("");
            }
        }
    }

//建立檔案處須加上.Close(); 否則會跳錯誤:
System.IO.IOException: '由於另一個處理序正在使用檔案'C:\TEST\log\xxxxxxxx.txt',所以無法存取該檔案。'

因所參考網路上的文章沒有加上,所以紀錄一下


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言