File Handling – Create and Retrieve Log File in C#.

In this tutorial, I will teach you how to create and retrieve a log file in c#. Logs are very important because it records every transaction that the system has executed. In this way, you can track the error made by the system. Let’s get started.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Add two RichTextBoxes, Label and a Button inside the Form just like shown below. ps2

Step 3

Press F7 to open the code editor. In the code editor, create a method for creating a Log File.
  1.  
  2. public static void Write_Log(string logMSG)
  3. {
  4. string string_Path = Application.StartupPath + "\\" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
  5. FileInfo file_info = new FileInfo(string_Path);
  6. DirectoryInfo dir_info = new DirectoryInfo(file_info.DirectoryName);
  7. if (!dir_info.Exists) dir_info.Create();
  8. using (FileStream file_Stream = new FileStream(string_Path, FileMode.Append))
  9. {
  10. using (StreamWriter log = new StreamWriter(file_Stream))
  11. {
  12. log.WriteLine(logMSG);
  13.  
  14.  
  15. }
  16. }
  17. }s

Step 4

Create a method for retrieving a Log File.
  1.  
  2. public static void show_Logs(RichTextBox txt)
  3. {
  4. string strPath = Application.StartupPath + "\\" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
  5. if (File.Exists(strPath))
  6. {
  7. StreamReader sReader = new StreamReader(strPath);
  8. txt.Text = sReader.ReadToEnd();
  9. sReader.Close();
  10. }
  11. else
  12. {
  13. MessageBox.Show("File not exist.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  14. }
  15. }

Step 5

Add the following code to retrieve a Log File and display it in the RichTextBox in the first load of the form.
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4. show_Logs(richTextBox2);
  5.  
  6. }
Double click a Button and add the following code for inserting/appending the text message logs and retrieving automatically when the button is clicked
  1.  
  2. Write_Log(richTextBox1.Text);
  3. richTextBox1.Clear();
  4.  
  5. show_Logs(richTextBox2);
The complete source code is included. You can download it and run it on your computer. 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