写日志

╄→尐↘猪︶ㄣ 提交于 2020-01-18 10:32:37

 /// <summary>
        /// 写日志文件
        /// </summary>
        /// <param name="sMsg"></param>
        public  void WriteLog(string sMsg, string fileType)
        {
            if (sMsg != "")
            {
                string directoryPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\log";
                //string directoryPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath+"\\log";// System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
                //+"\\log";//路径
                string filename = DateTime.Now.ToString("yyyyMMdd") + fileType + ".log";//文件名
              
                try
                {
                    if (!Directory.Exists(directoryPath))//验证是否有路径
                    {
                        Directory.CreateDirectory(directoryPath);
                    }

                    FileInfo fi = new FileInfo(directoryPath + "\\" + filename);
                    if (!fi.Exists)
                    {
                        using (StreamWriter sw = fi.CreateText())
                        {
                            sw.WriteLine(DateTime.Now + "\n" + sMsg + "\n");
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = fi.AppendText())
                        {
                            sw.WriteLine(DateTime.Now + "\n" + sMsg + "\n");
                            sw.Close();
                        }
                    }
                }
                catch
                { }
            }
        }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!