c#寫日誌
阿新 • • 發佈:2020-08-07
public void WriteLog(string msg) { string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; try { using (StreamWriter sw = File.AppendText(logPath)) { sw.WriteLine("訊息:" + msg); sw.WriteLine("時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sw.WriteLine("**************************************************"); sw.WriteLine(); sw.Flush(); sw.Close(); sw.Dispose(); } }catch (IOException e) { using (StreamWriter sw = File.AppendText(logPath)) { sw.WriteLine("異常:" + e.Message); sw.WriteLine("時間:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")); sw.WriteLine("**************************************************"); sw.WriteLine(); sw.Flush(); sw.Close(); sw.Dispose(); } } }