How to Write Log File in C#

Submitted by: 
Visitors have accessed this post 207 times.

In this tutorial, I will teach you how to create a log file in c#.net. Writing a log is very important in every transaction that has been made. In this way you can track if the transaction has an error and how to determine where the error occurs. See the procedure below.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application in c#.
log123

Step 2

Add a Button inside the form.
log321

Step 3

Go to the code view and create a method for creating a log file.

  1. public static void WriteLog(string logMessage)
  2. {
  3. string stringLogPath = @"C:\TransactionLogs\ActionLog-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
  4. FileInfo log_FileInfo = new FileInfo(stringLogPath);
  5. DirectoryInfo log_DirInfo = new DirectoryInfo(log_FileInfo.DirectoryName);
  6. if (!log_DirInfo.Exists) log_DirInfo.Create();
  7. using (FileStream file_Stream = new FileStream(stringLogPath, FileMode.Append))
  8. {
  9. using (StreamWriter log = new StreamWriter(file_Stream))
  10. {
  11. log.WriteLine(logMessage);
  12. }
  13. }
  14. }

Step 4

Write this code for the button.

  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. WriteLog("The button is clicked!");
  4. }

For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.