how to save exception in txt file?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)