C# .NET写入记事本(规范版)

指定Log文件夹下面,按照月份归类,每天一个日志,如下图:

 

代码如下:

 

        public static string getServerPath(string ServiceName)
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;
            currentPath = currentPath.Substring(0, currentPath.LastIndexOf("\\")); //取出最后一个\
            currentPath = currentPath.Substring(0, currentPath.LastIndexOf("\\")); //去除最后一个\
            currentPath = currentPath.Substring(0, currentPath.LastIndexOf("\\")); //去除最后一个\
            currentPath += "\\Log";
            if (Directory.Exists(currentPath))
            {
                string strDate = DateTime.Now.ToString("yyyyMM");
                currentPath += "\\" + ServiceName;
                if (Directory.Exists(currentPath))
                {
                    currentPath += "\\" + strDate;
                    if (Directory.Exists(currentPath))
                    {
                        currentPath += "\\" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                        if (File.Exists(currentPath))
                        {
                            return currentPath;
                        }
                        else
                        {
                            FileStream fs = File.Create(currentPath);
                            fs.Flush();
                            fs.Close();
                            return currentPath;
                        }
                    }
                    else
                    {
                        Directory.CreateDirectory(currentPath);
                        currentPath += "\\" + DateTime.Now.ToString("yyyyMMdd") + ".log";

                        FileStream fs = File.Create(currentPath);
                        fs.Flush();
                        fs.Close();
                        return currentPath;
                    }
                }
                else
                {
                    Directory.CreateDirectory(currentPath);
                    currentPath += "\\" + strDate;
                    Directory.CreateDirectory(currentPath);
                    currentPath += "\\" + DateTime.Now.ToString("yyyyMMdd") + ".log";

                    FileStream fs = File.Create(currentPath);
                    fs.Flush();
                    fs.Close();
                    return currentPath;
                }
            }
            else
            {
                return currentPath + "\\WxServerLog.log";
            }
        }

 

使用:

 

string logPath_Report = getServerPath("WxService");
File.AppendAllText(logPath_Report, string.Format("【{0}】服务启动!!\r\n", DateTime.Now));

 

 getServerPath("WxService")                                               //调用方法,WxService是文件夹名称

 

posted @ 2018-12-12 10:06  Quentin-wy  阅读(532)  评论(0编辑  收藏  举报