如何在txt文件中保存异常? [英] how to save exception in txt file?

查看:94
本文介绍了如何在txt文件中保存异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here, I want to save an Exception in "C:\" ..I am trying In DAL... How to save the Exception In C drive Error.txt

推荐答案

由于要将异常保存到 C:\Error.txt ,因此不需要目录。存在 Directory.CreateDirectory Server.MapPath(〜/ Error.txt)。您可以像这样使用 StreamWriter

Since you want to save the exception to C:\Error.txt, you don't need Directory.Exists, Directory.CreateDirectory, or Server.MapPath("~/Error.txt"). You can simply use StreamWriter like this:

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 (如果已经存在)。

The above code will create C:\Error.txt if it doesn't exist, or append C:\Error.txt if it already exists.

这篇关于如何在txt文件中保存异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆