How to Read Data from a Text File using C#

Today, I will teach you to create a program that can read the data from a text file using C#. Now, let's start this tutorial! 1. Open Notepad. Put any data in there, for example, i have write "Sourcecodester is the best!". Save it to the C directory with folder named file and named it as data.txt. data.txt 2. Create a Windows Form Application in C# for this tutorial by following the following steps in Microsoft Visual Studio: Go to File, click New Project, and choose Windows Application. 3. Next, add only one Button named btnRead and labeled it as "Read". Insert two textboxes named txtInput for inputting the source file and path of the text file that we wanted to read, and txtOutput to display the content of our text file. You must design your interface like this: design 4. In your btnRead, put this code below. Create a string variable named pathfile that will hold the text inputted in txtInput.
  1. string pathfile = txtInput.Text;
Initialize the System.IO.StreamReader having a file variable. This will locate the file and path of our inputted source.
  1. System.IO.StreamReader File = new System.IO.StreamReader(pathfile);
Code for reading the file.
  1. string data = File.ReadToEnd();
Close your file.
  1. File.Close();
Display the content of our file and will be viewed in txtOutput.
  1. txtOutput.Text = data;
Full source code:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8.  
  9. namespace Read_Data_from_TextFile_CSharp
  10. {
  11. public partial class Form1 : Form
  12. {
  13. public Form1()
  14. {
  15. InitializeComponent();
  16. }
  17.  
  18. private void btnRead_Click(object sender, EventArgs e)
  19. {
  20. // change the path of your file
  21.  
  22. // string pathfile = @"C:/files/data.txt";
  23. string pathfile = txtInput.Text;
  24. System.IO.StreamReader File = new System.IO.StreamReader(pathfile);
  25.  
  26. string data = File.ReadToEnd();
  27. File.Close();
  28. txtOutput.Text = data;
  29. }
  30. }
  31. }
Press "F5" to run the program. Output: output Hope this helps! :) Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment