In this article, i will show you how can we read text from a external .txt file in C#. For this purpose, I will be using StreamReader Class for reading text from external txt file.
Instructions:
- Start by adding following namespace to your code file.
using System.IO; - After that add the following code, where you want to read text from a file. This code will read all the text present in the file, line by line.
try
{
using (StreamReader sr = new StreamReader("file.txt")) // replace the file.txt with the exact location of your file.
{
String line;
while ((line = sr.ReadLine()) != null)
//sr.ReadLine() reads text line by line
// and every time it reads a line, it places cursor in the next line.
// So we will read the text to the last line and after that this function return null value.
{
Console.WriteLine(line);
}
}
}
catch (Exception ex)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(ex.Message);
} - If you want to check that whether the file you specified exists or not, you can use the following code for that purpose.
if (!File.Exists("file.txt")) // replace the file.txt with the exact location of your file.
{
return;
}
Incoming search terms:
- streamreader 2012 (1)