C#手寫日志(txt格式)


此方法僅提供在項目本地寫入TXT,方法中提供了客戶端及web端獲取項目路徑方法,可根據自己實際需求改寫路徑,一般用於未引入日志插件的項目和臨時服務器調試錯誤輸出

 

        /// <summary>
        /// 寫日志(txt格式)
        /// </summary>
        /// <param name="content">日志內容</param>
        public static void WriteLog(string content) 
        {
            string root = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string path = root.Remove(root.LastIndexOf('\\') + 1) + "Crane" + "\\Current\\" + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";//客戶端路徑(自定義路徑,如果沒有下面會創建)
            //string path = HttpContext.Current.Server.MapPath("~/" + 具體文件夾可多層);//web端路徑(自定義路徑,如果沒有下面會創建)
            DirectoryInfo directory = new DirectoryInfo(path);
            if (!directory.Exists)//不存在
            {
                directory.Create();
            }
            path = path + "/" + "文件名" + ".txt";
            StreamWriter sw = null;
            if (!File.Exists(path))
            {
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs);
                sw.WriteLine(content);
                sw.Close();
                fs.Close();
            }
            else
            {
                sw = File.AppendText(path);
                sw.WriteLine(content);
                sw.Close();
            }
        }

 

End...

 


免責聲明!

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



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