C#写日志

来源:互联网 发布:淘宝古玩网 编辑:程序博客网 时间:2024/06/05 00:29
//写日志
        public static void LogInfo(string msg)
        {
            string uploadPath = HttpContext.Current.Server.MapPath("Log") + "\\";
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            string fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";


            FileStream fs;
            StreamWriter sw;
            string sFileName = uploadPath + fileName;
            if (File.Exists(sFileName))
            //验证文件是否存在,有则追加,无则创建
            {
                fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
            }
            else
            {
                fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
            }
            sw = new StreamWriter(fs);
            msg = String.Format("------------------------{0}------------------------------\r\n", DateTime.Now) + msg;
            msg += "\r\n";
            sw.WriteLine(msg);
            sw.Close();
            fs.Close();    
        }