As all we know there are three most efficient ways to read the content of a file in C#.Net. They as follow:
- File.ReadAllText: This method of reading is appropriate for reading the text file in small size.
- File.ReadAllLines: This method of reading file is appropriate for reading the file of size small and medium.
- StreamReader: This methos is used for reading the file of very large size. This method does not read all the content of the file in the memory. It read line by line.
Here in our tutorial, we will use StreamReader to read the text file because we are going to use a text file almost of 1GB in size.
Please check the below given code. Console.WriteLine("******READ TEXT FILE******");
string filePath = "C:\\Personal\\Codemantra99.com\\Articles\\TesttextFile.txt";
if (File.Exists(filePath))
{
StreamReader strreader = new StreamReader(filePath);
string linetext;
while ((linetext = strreader.ReadLine()) != null)
{
Console.WriteLine(linetext);
}
}
else
{
Console.WriteLine("sorry file not found...");
}
Console.ReadLine();
Here in above code, I have taken the path of the text file in a string variable, and I have used File.Exists method to validate first whether the file exists or not. If file does not exist on that case, it will display an error message to user.Now I have created object of the StreamReader to read the file in memory stream. Now above as I mention StreamReader is the most efficient way to read the large text file, in next line we are reading each line of the text file at run time and displaying it. You can collect as per you convince. Now let's place a break point and check the output.
Note
1. The above output taken me only less then 1 sec to get the result.
2. To make you sample text file open the notepad and copy past the content of the file again and again until you get the desired size of the text file.
2. To make you sample text file open the notepad and copy past the content of the file again and again until you get the desired size of the text file.