C# Exception 写入文件
/// <summary> /// 将异常打印到LOG文件 /// </summary> /// <param name="ex">异常</param> public static void WriteLog(Exception ex) { //如果日志文件为空,则默认在Debug目录下新建YYYY-mm-dd_Log.log文件 string LogAddress = Environment.CurrentDirectory + '\\' + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + "_Log.log"; if (!File.Exists(LogAddress)) { FileStream fs = new FileStream(LogAddress, FileMode.Create, FileAccess.Write); //把异常信息输出到文件 StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); sw.WriteLine("当前时间:" + DateTime.Now.ToString()); sw.WriteLine("异常信息:" + ex.Message); sw.WriteLine("异常对象:" + ex.Source); sw.WriteLine("调用堆栈:" + ex.StackTrace.Trim()); sw.WriteLine("触发方法:" + ex.TargetSite); sw.WriteLine(); sw.Close(); fs.Close(); } else { //把异常信息输出到文件 FileStream fs = new FileStream(LogAddress,FileMode.Open,FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.WriteLine("当前时间:" + DateTime.Now.ToString()); sw.WriteLine("异常信息:" + ex.Message); sw.WriteLine("异常对象:" + ex.Source); sw.WriteLine("调用堆栈:" + ex.StackTrace.Trim()); sw.WriteLine("触发方法:" + ex.TargetSite); sw.WriteLine(); sw.Close(); fs.Close(); } }