Home > DeveloperSection > Blogs > How to Create Log File in C#

How to Create Log File in C#

C# C# 
5 Comment(s)
 70141  View(s)
Rate this:

How to Create Log File in C#

In this blog I have described how to create log file in C#. Log file can be simple text file, XML document or we can also use tables in database to create log. Here I have used .txt file. In this file we have stored information about generated exception of application. Using this log file we have easily find out error list. In this file we have stored information according our requirement. For example in log file we have stored file name, exception name, date and time, error line number, event name, Controls name etc.

Now let’s to implementation

Step 1: Write down below line of code in global area within your application such that global class or used it as global.

public void LogFile(string sExceptionName, string sEventName, string sControlName, int       nErrorLineNo, string sFormName)


            StreamWriter log;

            if (!File.Exists("logfile.txt"))


                log = new StreamWriter("logfile.txt");




                log = File.AppendText("logfile.txt");


            // Write to the file:

            log.WriteLine("Data Time:" + DateTime.Now);

            log.WriteLine("Exception Name:" + sExceptionName);

            log.WriteLine("Event Name:" + sEventName);

            log.WriteLine("Control Name:" + sControlName);

            log.WriteLine("Error Line No.:" + nErrorLineNo);

            log.WriteLine("Form Name:" + sFormName);

            // Close the stream:





·         Include System.IO namespace.

·         LogFile method call by catch section when any exception is triggered.

·         LogFile method takes five arguments that used to write within logfile.txt.

·         logfile.txt is file that stored in your application bin/debug folder.

Step 2: Write below ExceptionHelper class (line of code) that return occurred error line number.

public static class ExceptionHelper


        public static int LineNumber(this Exception e)


           int linenum = 0;



                linenum = Convert.ToInt32(e.StackTrace.Substring(e.StackTrace.LastIndexOf(":line") + 5));




                //Stack trace is not available!


            return linenum;



Step 3: Now put your line of code within try and catch blog and call LogFile method as below



                //put here your code


            catch (Exception exe)


               //call LogFile method and pass argument as Exception message, event name, control         name, error line number, current form name

                LogFile(exe.Message, e.ToString(), ((Control)sender).Name, exe.LineNumber(), this.FindForm().Name);


Step 4: If any exception is generated then LogFile.txt look like as below

Data Time:3/6/2013 4:29:47 PM

Exception Name:Input string was not in a correct format.Couldn't store <LineNumber> in salary Column.  Expected type is Double.

Event Name:System.Windows.Forms.MouseEventArgs

Control Name:btnUpdate

Error Line No.:106

Form Name:Opereation





Write Error Log or Exception Log into File in C# .NET

By Worl Traveler on   3 years ago

Generally we are not interested to show any type of application error to end user. Error logs are very important for collecting all error data generated by an application. It is more useful during an early or beta release of a product.

That’s why it is better to store any kind of exceptions in one place. This files can be send by email or others technology to developer. Time to time developer must analyze them and fix all the bugs without knowing clients. It will increase application performance.

A good solution with proper code about it is here: http://cybarlab.blogspot.com/2013/03/write-error-log-into-file-in-c-sharp.html

line number showing zero

By Ashfaque Hussain on   3 years ago
Line number is showing Zero when i keep exe file in other file apart from project file. can you please resolve it

Please go this link its very helpfull..

By Ramesh J on   one year ago

Simple and Great

By Furqan zafar on   one year ago
Fantastic. Works fine. Simple and to the point. Thanks

Combined with JavaScript for Cordova Plugin?

By George Campbell on   6 months ago
when creating apps through cordova, I am writing a file to the phone's hard drive. This is in JavaScript and HTML5 which converts to the native code e.g. either Java, XCode, C#. The plugin: https://www.npmjs.com/package/cordova-plugin-file allows to write blobs for all devices except windows phone. We are focusing on windows 10 mobile. I was wondering if anyone knows how to contribute to the plugin to allow 'FileWriter.write(blob)' to work with windows mobiles for that plugin.
Regards, George.

Don't want to miss updates? Please click the below button!

Follow MindStick