日志文件

/// <summary>
        /// 创建日志文件,每天一个
        /// </summary>
        /// <param name="logContent">日志内容 </param>
        public static void CreateInLog(string logContent)
        {
            string filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase+"Log\\";
            //string filePath = "E:\\Log";//路径:如 E:\
            filePath = filePath.EndsWith(@"\") ? filePath : (filePath + @"\");
            if (Directory.Exists(filePath) == false)
            {
                Directory.CreateDirectory(filePath);//判断该路径是否存在,不存在则创建该路径文件夹
            }

            DateTime dtNow = DateTime.Now;//获取当前日期
            string dateString = dtNow.Year.ToString();
            dateString += dtNow.Month.ToString().Length < 2 ? ("0" + dtNow.Month.ToString()) : (dtNow.Month.ToString());
            dateString += dtNow.Day.ToString().Length < 2 ? ("0" + dtNow.Day.ToString()) : (dtNow.Day.ToString());  //将日期格式转成yyyyMMdd的格式,如:20170921

            string filename = filePath + "Log_" + dateString + ".txt"; //创建文件名
            StreamWriter sw = null;

            if (File.Exists(filename))
            {
                sw = new StreamWriter(filename, true, System.Text.Encoding.GetEncoding("UTF-8"));
            }
            else
            {
                sw = new StreamWriter(filename, false, System.Text.Encoding.GetEncoding("UTF-8"));
            }

            StringBuilder dataRow = new StringBuilder("");
            dataRow.Append(DateTime.Now+"========"+logContent);
            sw.WriteLine(dataRow.ToString());//写入内容
            sw.Close();
        }

  

posted @ 2020-04-26 12:06  荧屏  阅读(124)  评论(0编辑  收藏  举报