C# 写日志文件

来源:互联网 发布:淘宝产品推广方法 编辑:程序博客网 时间:2024/05/16 10:37

        public static void WriteLog(string txt)

        {

            try

            {

                string path = Application.StartupPath + @"\log\" + DateTime.Now.ToString("yyyy-MM-dd") + @"\";

                if (!Directory.Exists(path))

                {

                    Directory.CreateDirectory(path);

                }

                path +=  DateTime.Now.ToString("yyyyMMdd") + "-" + DateTime.Now.ToString("HH") + ".txt";

                if (!File.Exists(path))

                {

                    File.Create(path);

                }

                FileStream fs;

                StreamWriter sw;

                fs = new FileStream(path, FileMode.Append);

                sw = new StreamWriter(fs, Encoding.Default);

                sw.Write(DateTime.Now.ToString("HH:mm:ss") + " " + txt + "\r\n");

                sw.Close();

                fs.Close();

            }

            catch (Exception ex)

            {

                WriteLog("程序发生异常(WriteLog)。详情:" + ex.Message);

            }

        }

原创粉丝点击