/// <summary> /// 写日志文件 /// </summary> /// <param name="Infos">日志内容</param> /// <param name="fileNameParam">文件名(不带后缀)</param> public static void WriteLog(string Infos, string fileNameParam) { try { StackTrace trace = new StackTrace(); MethodBase method = trace.GetFrame(1).GetMethod(); Infos = "[" + method.Name + "]" + Infos; } catch { } WriteLogFile(Infos, fileNameParam, ""); } /// <summary> /// 写日志文件 /// </summary> /// <param name="Infos">日志内容</param> /// <param name="fileNameParam">文件名(不带后缀)</param> /// <param name="filePathParam">附加子路径</param> public static void WriteLogFile(string Infos, string fileNameParam, string filePathParam) { FileStream fs = null; try { string filename = ""; //年月日 string str = System.DateTime.Now.Date.Year.ToString() + "-" + System.DateTime.Now.Date.Month.ToString() + "-" + System.DateTime.Now.Date.Day.ToString(); filename = AppDomain.CurrentDomain.BaseDirectory + "\Logs\" + filePathParam + "\" + str + fileNameParam + ".log"; //如果不存在该目录就创建该目录 if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\Logs\" + filePathParam + "\")) { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\Logs\" + filePathParam + "\"); } //如果该文件存在则往里面写日志 //ERROR: “System.Web.Mvc.Controller.File(string, string, string)”是一个“方法”,这在给定的上下文中无效 // 这是一个与Controller.File方法和System.IO.File类名称冲突的问题,只要完整输入明确类名就可解决。 if (System.IO.File.Exists(filename)) { fs = new FileStream(filename, FileMode.Open, FileAccess.Write); } else { fs = new FileStream(filename, FileMode.Create, FileAccess.Write); } byte[] Bt; string curLine; //时分秒+日志信息 curLine = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + " " + Infos + " "; Bt = new byte[curLine.Length * 2]; Bt = Encoding.UTF8.GetBytes(curLine); fs.Position = fs.Length; fs.Write(Bt, 0, Bt.Length); fs.Close(); } catch (Exception) { if (fs != null) { fs.Close(); } } }