如何将异常保存到文本文件中?

34
public DataTable InsertItemDetails(FeedRetailPL objFeedRetPL)
{
    DataTable GetListID = new DataTable();
    try
    {
        SqlParameter[] arParams = new SqlParameter[4];

        arParams[0] = new SqlParameter("@Date", typeof(DateTime));
        arParams[0].Value = objFeedRetPL.requestdate;

    }
    catch (Exception ex)
    {
        string dir = @"C:\Error.txt";  // folder location
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
            File.AppendAllText(Server.MapPath("~/Error.txt"), "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
       "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
            string New = Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine;
            File.AppendAllText(Server.MapPath("~/Error.txt"), New);
        }
    }
}

这里,我想在 "C:\" 中保存一个异常。 我正在尝试在DAL中...如何将异常保存在 C 驱动器的 Error.txt 文件中。


你从这段代码中得到了什么错误? - Steve
使用Log4Net进行日志记录。 - hkutluay
如何将异常保存在Txt文件中...我该怎么做? - Sambasiva
2
您不需要首先检查 Directory.Exist,而是可以直接使用 Directory.CreateDirectory(dir);,因为它只会在目录不存在时才创建。 - Tim Schmelter
5个回答

76

由于您想将异常保存到C:\ Error.txt,因此不需要使用Directory.ExistsDirectory.CreateDirectoryServer.MapPath(“〜/ Error.txt”)。您可以像这样简单地使用StreamWriter:

string filePath = @"C:\Error.txt";

Exception ex = ...

using( StreamWriter writer = new StreamWriter( filePath, true ) )
{
    writer.WriteLine( "-----------------------------------------------------------------------------" );
    writer.WriteLine( "Date : " + DateTime.Now.ToString() );
    writer.WriteLine();

    while( ex != null )
    {
        writer.WriteLine( ex.GetType().FullName );
        writer.WriteLine( "Message : " + ex.Message );
        writer.WriteLine( "StackTrace : " + ex.StackTrace );

        ex = ex.InnerException;
    }
}

如果C:\Error.txt文件不存在,上述代码将创建该文件,如果已存在,则将数据追加到C:\Error.txt中。


当我尝试创建新的StremWriter时,出现以下错误:客户端没有所需的特权。 - Christoph Adamakis
2
如果您的文件路径为 C:\Error.txt,那么您可能没有写入 C 盘根目录的权限。请尝试使用网站文件夹内的路径,例如 Server.MapPath("~/Error.txt") - ekad

8
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    namespace ErrorLoggingSample
    {
     class Program
      {
      static void Main(string[] args)
      {
        try
        {
            string str = string.Empty;
            if (string.IsNullOrEmpty(str))
            {
                throw new Exception("Wrong Data");
            }
        }
        catch (Exception ex)
        {
            ErrorLogging(ex);
            ReadError();
        }

    }

    public static void ErrorLogging(Exception ex)
    {
        string strPath = @"D:\Rekha\Log.txt";
        if (!File.Exists(strPath))
        {
            File.Create(strPath).Dispose();
        }
        using (StreamWriter sw = File.AppendText(strPath))
        {
            sw.WriteLine("=============Error Logging ===========");
            sw.WriteLine("===========Start============= " +       DateTime.Now);
            sw.WriteLine("Error Message: " + ex.Message);
            sw.WriteLine("Stack Trace: " + ex.StackTrace);
            sw.WriteLine("===========End============= " + DateTime.Now);

        }
    }

    public static void ReadError()
    {
        string strPath = @"D:\Rekha\Log.txt";
        using (StreamReader sr = new StreamReader(strPath))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
      }
   }
  }

这是对我有效的一个,上面的答案引发了另一个异常。 - Harvey Lin

2

I use that one

catch (Exception e)
{
    new MessageWriteToFile(e).WriteToFile();
}


public class MessageWriteToFile
{
    private const string Directory = "C:\\AppLogs";
    public string Message { get; set; }
    public Exception Exception { get; set; }
    public string DefaultPath
    {
        get
        {
            var appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            var folder = $"{Directory}\\{appName}";

            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }

            var fileName = $"{DateTime.Today:yyyy-MM-dd}.txt";
            return $"{Directory}\\{appName}\\{fileName}";
        }
    }

    public MessageWriteToFile(string message)
    {
        Message = message;
    }

    public MessageWriteToFile(Exception ex)
    {
        Exception = ex;
    }

    public bool WriteToFile(string path = "")
    {
        if (string.IsNullOrEmpty(path))
        {
            path = DefaultPath;
        }

         try
        {
            using (var writer = new StreamWriter(path, true))
            {
                writer.WriteLine("-----------------------------------------------------------------------------");
                writer.WriteLine("Date : " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
                writer.WriteLine();

                if (Exception != null)
                {
                    writer.WriteLine(Exception.GetType().FullName);
                    writer.WriteLine("Source : " + Exception.Source);
                    writer.WriteLine("Message : " + Exception.Message);
                    writer.WriteLine("StackTrace : " + Exception.StackTrace);
                    writer.WriteLine("InnerException : " + Exception.InnerException?.Message);
                }

                if (!string.IsNullOrEmpty(Message))
                {
                    writer.WriteLine(Message);
                }

                writer.Close();
            }
        }
        catch (Exception)
        {
            return false;
        }

        return true;
    }
}

1

string[] path1 = Directory.GetFiles(@"E:\storage", "*.txt");//它从文件夹中获取所有文本文件

                for (var i = 0; i < path1.Length; i++)
                {
                var file = Directory.GetDirectories(networkPath);

                

                    var path = file;
                string temp_FilePath = "E:\\temp.txt";
                string temp_FilePath1 = @"E:\ExceptionFiles\Cs_regular\\Cs_regular.txt";
                string temp_FilePath2 = @"E:\ExceptionFiles\CC_eBilling\\CC_eBilling.txt";
                string folder = @"E:\ExceptionFiles\Cs_regular";
                string folder1 = @"E:\ExceptionFiles\CC_eBilling";



                string[] lines;
                var list = new List<string>();
                var list1 = new List<string>();
                var list2 = new List<string>();
                var error = false;
                var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
                var fileStream1 = new FileStream(path, FileMode.Open, FileAccess.Read);
                var fileStream2 = new FileStream(path, FileMode.Open, FileAccess.Read);




                using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
                {
                    string line;



                    while ((line = streamReader.ReadLine()) != null)
                    {


                        var res = line.Substring(20, 16);
                        //var timenow = DateTime.Now.ToString("yyyy /MM/dd HH:mm");
                        var timenow1 = "2020/10/31 10:11";

                        if (res == timenow1)
                        {

                            string linesRemoved = "ERROR";

                            if (!line.Contains(linesRemoved))
                            {

                                if (error == true)
                                {
                                    if (line.Contains("at"))
                                    {
                                        list1.Add(line);
                                        error = true;
                                    }
                                    else
                                    {
                                        error = false;
                                    }
                                }

                            }
                            else
                            {
                                error = false;
                            }




                            if (line.Contains("Exception1") && error == false)
                            {
                                list1.Add(line);
                                error = true;
                            }

                        }



                    }
                }

                

                using (var streamReader2 = new StreamReader(fileStream2, Encoding.UTF8))
                {
                    string line;
                    while ((line = streamReader2.ReadLine()) != null)
                    {
                        string linesRemoved = "ERROR";
                        var res = line.Substring(20, 16);
                        //var timenow = DateTime.Now.ToString("yyyy/MM/dd HH:mm");
                        var timenow1 = "2020/10/29 12:38";
                        if (res == timenow1)
                        {

                            if (!line.Contains(linesRemoved))
                            {
                                if (error == true)
                                {
                                    if (line.Contains("at"))
                                    {

                                        list2.Add(line);
                                        error = true;
                                    }
                                    else
                                    {
                                        error = false;
                                    }
                                }
                            }
                            else
                            {
                                error = false;
                            }



                            if ((line.Contains("Exception2") && line.Contains("Exception:")) && error == false)
                            {
                                list2.Add(line);
                                error = true;

                            }
                        }






                    }
                }




                if ((System.IO.File.Exists(temp_FilePath1) || System.IO.File.Exists(temp_FilePath2)))
                {

                    int fileCount = Directory.GetFiles(folder).Length;
                    int fileCount1 = Directory.GetFiles(folder1).Length;
                    fileCount++;
                    fileCount1++;
                    temp_FilePath1 = temp_FilePath1 + "(" + fileCount.ToString() + ").txt";
                    temp_FilePath2 = temp_FilePath2 + "(" + fileCount1.ToString() + ").txt";


                }
                {
                    System.IO.File.WriteAllLines(temp_FilePath1, list1);
                    System.IO.File.WriteAllLines(temp_FilePath2, list2);

                }





                System.IO.File.WriteAllLines(temp_FilePath, list);

                System.IO.File.WriteAllLines(temp_FilePath1, list1);
                System.IO.File.WriteAllLines(temp_FilePath2, list2);

                }

            }
        }
        catch (Exception ex)
        {

        }



        return null;

将日志文件中的异常分离出来并存储到另一个文本文件中,并在文件夹中创建一个文本文件。 - Akurathi-sandeep Aurathi
请为您的代码添加一些描述,以便他人易于理解。 - Procrastinator
在最后一个“if”语句中,它会自动创建包含文件夹中所有已准备好的文件的文本文件,并增加文件名的编号,例如cs_regular1和cs_regular2。 - Akurathi-sandeep Aurathi

1
尝试这个。
 try
    {
        int i = int.Parse("Prashant");
    }
    catch (Exception ex)
    {
        this.LogError(ex);
    }

   private void LogError(Exception ex)
   {
    string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
    message += Environment.NewLine;
    message += "-----------------------------------------------------------";
    message += Environment.NewLine;
    message += string.Format("Message: {0}", ex.Message);
    message += Environment.NewLine;
    message += string.Format("StackTrace: {0}", ex.StackTrace);
    message += Environment.NewLine;
    message += string.Format("Source: {0}", ex.Source);
    message += Environment.NewLine;
    message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
    message += Environment.NewLine;
    message += "-----------------------------------------------------------";
    message += Environment.NewLine;
    string path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
    using (StreamWriter writer = new StreamWriter(path, true))
    {
        writer.WriteLine(message);
        writer.Close();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接