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.
- Start by adding following namespace to your code file.
- 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.
using (StreamReader sr = new StreamReader("file.txt")) // replace the file.txt with the exact location of your file.
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.
catch (Exception ex)
Console.WriteLine("The file could not be read:");
- 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.
Incoming search terms:
- streamreader 2012 (1)