C# 根目录创建日志

1. 从根目录创建日志文件夹

2. 文件夹中创建 日志txt

 

        public static void SetSystemLog(string czlr, string pathname = "log", string filename = "SystemLog")
        {
            StreamWriter m_streamWriter = null;
            FileStream fs = null;
            try
            {
                Monitor.Enter(m_syn);
                string pathphe = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase+"\\" + pathname;
                if (!System.IO.Directory.Exists(pathphe))
                {
                    System.IO.Directory.CreateDirectory(pathphe);
                }
                String FileName = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + pathname + "\\" + System.DateTime.Today.Year.ToString() + System.DateTime.Today.Month.ToString().PadLeft(2, '0') + System.DateTime.Today.Day.ToString().PadLeft(2, '0') + filename + ".txt";
                fs = new FileStream(@FileName, FileMode.OpenOrCreate, FileAccess.Write);
                m_streamWriter = new StreamWriter(fs);
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);

                m_streamWriter.WriteLine(DateTime.Now.ToString() + "内容:" + czlr);
                m_streamWriter.Flush();

            }
            catch
            {
            }
            finally
            {
                try
                {
                    if (m_streamWriter != null)
                    {
                        m_streamWriter.Close();
                    }
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    m_streamWriter = null;
                    fs = null;
                }
                catch { }
                Monitor.Exit(m_syn);
            }
        }

 

posted @ 2021-11-17 14:33  lglmvp  阅读(179)  评论(0编辑  收藏  举报