c#寫日志


方法一:以日期為日志文件名,輸出txt文件

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(); 
        } 
    } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM