`

C#一个简单写日志文件的类

    博客分类:
  • C#
 
阅读更多
 /// <summary>
    /// Log 的摘要说明。
    /// </summary>
    public sealed class Log
    {
        public Log()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        ~Log()
        {

        }

        static StreamWriter CreateLogFile(string FileName)
        {
            string Path = Application.StartupPath + "\\Log";
            if (!Directory.Exists(Path))
                Directory.CreateDirectory(Path);

            string FilePath = string.Format("{0}\\{1} {2:yyyyMMdd}.log", Path, FileName, DateTime.Today);

            if (!File.Exists(FilePath))
                return File.CreateText(FilePath);

            return File.AppendText(FilePath);
        }

        public static void WriteErrorInfo(string s, Exception ex)
        {
            lock (thisLock)
            {
                StreamWriter SW = CreateLogFile("Error");

                SW.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "  " + s);
                SW.WriteLine(ex.Message);
                SW.WriteLine(ex.StackTrace);
                Write(s);
            }
        }

        private static Object thisLock = new Object();
        public static void Write(string s)
        {
            string sFileName = null;
            StreamWriter SW;
            lock (thisLock)
            {
                sFileName = Application.StartupPath + "\\Log";
                if (!Directory.Exists(sFileName)) Directory.CreateDirectory(sFileName);

                sFileName = string.Format("{0}\\Log\\{1:yyyyMMdd}.log", Application.StartupPath, DateTime.Today);
                if (!File.Exists(sFileName))
                    SW = File.CreateText(sFileName);
                else
                    SW = File.AppendText(sFileName);
                SW.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "  " + s);
                SW.Close();
            }
        }

        public static void ThrowException(string ErrMsg)
        {
            Write(ErrMsg);
            throw new Exception(ErrMsg);
        }

        public static void Read(string filename, ref string sMsg)
        {
            string sFileName = null;

            sFileName = Application.StartupPath + "\\Log";
            if (!Directory.Exists(sFileName)) Directory.CreateDirectory(sFileName);

            sFileName = string.Format("{0}\\Log\\{1}", Application.StartupPath, filename); // + ".log"

            if (!File.Exists(sFileName)) return;
            
            StreamReader SR;
            string S;
            SR = File.OpenText(sFileName);
            S = SR.ReadLine();
            while (S != null)
            {
                sMsg += S + "\r\n";
                S = SR.ReadLine();
            }
            SR.Close();
        }
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics