Friday 24 April 2015

How to write a Exception to Text file in c# asp.net

Here I am writing a program, program, throw a exception in try block then it catch by catch block.
finally pass this exception to method called writeInFile(string excep) and this method will write
the thrown exception in text file in the base directory by default.

source code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;

namespace ConsoleDemoApp
{
    class WriteException
    {
        /* program to write a exception in c# */
       
        static void Main(string[] args)
        {
            int numerator=100;
            int Denominator=0;
            try{
                // throw a exception
                 int result=   numerator/Denominator;
                 Console.ReadKey();
               }
            catch(Exception ex)
            {
                //catch the exception and write to txt file
                writeInFile(ex.ToString());
            }
           
        }

        static void writeInFile(string excep)
        {
            // it will get base directory path but you can change it.
            string path = AppDomain.CurrentDomain.BaseDirectory;
            String dir = Path.GetDirectoryName(path);
            dir += "\\Error\\";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string newFileName = string.Format("{0:dd-MMM-yyyy_hh-mm-ss-tt}" + ".txt", DateTime.Now);
            string filepath = dir + newFileName;
            if (!File.Exists(filepath))
            {
                File.Create(filepath).Close();
            }
            using (StreamWriter w = File.AppendText(filepath))
            {
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Excepation :" + excep;
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
    }
}

Output



No comments:

Post a Comment