how to save exception in txt file?

前端 未结 5 1125
逝去的感伤
逝去的感伤 2021-01-31 16:46
public DataTable InsertItemDetails(FeedRetailPL objFeedRetPL)
{
    DataTable GetListID = new DataTable();
    try
    {
        SqlParameter[] arParams = new SqlParamet         


        
5条回答
  •  野的像风
    2021-01-31 17:08

    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;
        }
    }
    

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

提交回复
热议问题