Home
C# Read Text File Line By Line
Reading a text file is quite easy, you can read the whole lot into a string or read one line at a time. This is for reading one line at a time.
Start out with System IO at the top
using System.IO;
Then set a the file name, check the file exists, set up a streamreader then read!
string MyFile = "C:\MyFolder\MyFile.txt"
StreamReader MyStreamReader = new StreamReader(MyFile);
string Line1 = MyStreamReader.ReadLine();
string Line2 = MyStreamReader.ReadLine();
string Line3 = MyStreamReader.ReadLine();
...
This is great for simple text files where you know the format and what to expect. It's a bit long winded if there's a lot of lines. You can loop through all the lines though until you run out of lines. Take note of the many brackets in the while setup.
string MyFile = "C:\MyFolder\MyFile.txt"
StreamReader MyStreamReader = new StreamReader(MyFile);
string MyLine = "";
while((MyLine = MyStreamReader.ReadLine()) != null){
//MyLine is this line of text for you to process however you need
MyTextBox.Text = MyLine + " XX ";
}
Reader's Comments
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home