C#手写日志(txt格式)

此方法仅提供在项目本地写入TXT,方法中提供了客户端及web端获取项目路径方法,可根据自己实际需求改写路径,一般用于未引入日志插件的项目和临时服务器调试错误输出

        /// <summary>
        /// 写日志(txt格式)
        /// </summary>
        /// <param name="content">日志内容</param>
        public static void WriteLog(string content) 
        {
            string root = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string path = root.Remove(root.LastIndexOf('\') + 1) + "Crane" + "\Current\" + "\" + DateTime.Now.ToString("yyyyMMdd") + "\";//客户端路径(自定义路径,如果没有下面会创建)
            //string path = HttpContext.Current.Server.MapPath("~/" + 具体文件夹可多层);//web端路径(自定义路径,如果没有下面会创建)
            DirectoryInfo directory = new DirectoryInfo(path);
            if (!directory.Exists)//不存在
            {
                directory.Create();
            }
            path = path + "/" + "文件名" + ".txt";
            StreamWriter sw = null;
            if (!File.Exists(path))
            {
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs);
                sw.WriteLine(content);
                sw.Close();
                fs.Close();
            }
            else
            {
                sw = File.AppendText(path);
                sw.WriteLine(content);
                sw.Close();
            }
        }

End...

原文地址:https://www.cnblogs.com/zyg316/p/15473970.html