Read a certain line in a text file






2.47/5 (25 votes)
Nov 4, 2005
2 min read

127953

1057
Read a certain line in your text files by making an array
Introduction
This Article will show you how to read a line in a text file. We will write a small class that will take the file that you have loaded and number of lines you want to load. I tired to make this simple as possible.
The Code
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ReadLine
{
class Program
{
static void Main(string[] args)
{
//Load our text file
TextReader tr = new StreamReader("\\test.txt");
//How many lines should be loaded?
int NumberOfLines = 15;
//Make our array for each line
string[] ListLines = new string[NumberOfLines];
//Read the number of lines and put them in the array
for (int i = 1; i < NumberOfLines; i++)
{
ListLines[i] = tr.ReadLine();
}
//This will write the 5th line into the console
Console.WriteLine(ListLines[5]);
//This will write the 1st line into the console
Console.WriteLine(ListLines[1]);
Console.ReadLine();
// close the stream
tr.Close();
}
}
}
The Code - Explained
I'll now take the time to let you know what is going on in the code.
TextReader tr = new StreamReader("\\test.txt");
This will just load the text file into the program, make sure that you rename it to whatever your file is.
int NumberOfLines = 15;
string[] ListLines = new string[NumberOfLines];
The NumberOfLines
will hold the number of lines you want to load into the array. The ListLines
makes our array that will hold each line from our text file.
Note: Make sure that you add one to NumberOfLines
, if you have a total of 5 lines make NumberOfLines
equal 6.
for (int i = 1; i < NumberOfLines; i++)
{
ListLines[i] = tr.ReadLine();
}
This is the main part of the program that will put each line of code into the ListLines
array. This will allow us to call each line whenever we want to.
Console.WriteLine(ListLines[5]);
Console.WriteLine(ListLines[1]);
All you have to do now is use ListLines[NumberLineYouWant] and you can do whatever you want with it.
My Small Background
This is my fist article I've made. I started C# about 2 weeks ago. This might not be the best way (For example you need to get to the 50,000th line in a text file, you'll have to make an array that will hold 50,000 lines of text). I started programming in PHP at the age of 12 (I'm 14 now). Ever since that I've always wanted to learn a new language. I've played with C++ then I started coding in C. To me C was much easier that C++. I have also played with ASP and ASP.NET, but since I was good at PHP, I couldn't find a reason for those languages. Now, here I am with C#, which to me is far easier then C or C++.