Write a Log file in .Net Application

In application development environment we always require to track our application performance as well as error and bugs. To tracking bugs and error we always write the log in temporary folder. So today we are going to discuss how to write the log in .Net application. Writing log not only saves our time as well as helps us to track our application in proper manner.
 
So in this blog I will tell you how to write the log using C# programming language.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace BackToBasicProj  
  9. {  
  10.     class WriteLogFile  
  11.     {  
  12.         public static bool WriteLog(string strFileName,string strMessage)  
  13.         {  
  14.             try  
  15.             {  
  16.                 FileStream objFilestream = new FileStream(string.Format("{0}\\{1}", Path.GetTempPath(), strFileName), FileMode.Append, FileAccess.Write);  
  17.                 StreamWriter objStreamWriter = new StreamWriter((Stream)objFilestream);  
  18.                 objStreamWriter.WriteLine(strMessage);  
  19.                 objStreamWriter.Close();  
  20.                 objFilestream.Close();  
  21.                 return true;  
  22.             }  
  23.             catch(Exception ex)  
  24.             {  
  25.                 return false;  
  26.             }  
  27.         }  
  28.     }  

Now calling WriteLog method form Program.cs file.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace BackToBasicProj  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             WriteLogFile.WriteLog("ConsoleLog", String.Format("{0} @ {1}""Log is Created at", DateTime.Now));  
  14.             Console.WriteLine("Log is Written Successfully !!!");  
  15.             Console.ReadLine();  
  16.         }  
  17.     }  

Now run this !!!
 
 
 
And now check your Temp folder where the file is created with name "ConsoleLog".
 
Press-> window+r
 
Type Temp then click ok to see the log file.
 
 
 
Now open with notepad.
 
Done!!!
 
Hope you Enjoy with this. Comment your feedback.
Ebook Download
View all
Learn
View all