Pages

Men

rh

6/17/2012

Error Logging in C#

  public static void LogException ( string exceptionMessage , string applicationPath )
        {
            string exceptionFile = applicationPath + "\\ExceptionLog" + DateTime . Now . ToString ( "MMddyyyy" ) + ".txt";
            FileStream fsError = null;
            StreamWriter sw = null;
            try
            {
                if ( File . Exists ( exceptionFile ) )
                {
                    fsError = new FileStream ( exceptionFile , FileMode . Append , FileAccess . Write );
                    sw = new StreamWriter ( fsError );
                    sw . WriteLine ( Environment . NewLine + "------------------------------" + Environment . NewLine );
                    sw . WriteLine ( exceptionMessage );
                }
                else
                {
                    fsError = new FileStream ( exceptionFile , FileMode . Create , FileAccess . Write );
                    sw = new StreamWriter ( fsError );
                    sw . WriteLine ( exceptionMessage );
                }
                sw . Flush ( );

            }
            catch ( Exception exc )
            {
                MessageBox . Show ( exc . Message , "Error In Logging" , MessageBoxButtons . OK , MessageBoxIcon . Error );
            }
            finally
            {
                sw . Close ( );
                fsError . Close ( );
                sw . Dispose ( );
                fsError . Dispose ( );
                MessageBox . Show ( exceptionMessage + Environment . NewLine + Environment . NewLine + "Please report to the programmer any persistent error.   " , "Error Encountered" , MessageBoxButtons . OK , MessageBoxIcon . Error );
            }
        }

No comments :

Post a Comment