Use the StreamReader class to read a text file using C#
A simple example of how to use the StreamReader class to read a text file using C#.
Code:
using System;
using System.IO;
namespace ConsoleApplications
{
class StreamReaderDemo
{
static void Main(string[] args)
{
string pathFile = "book.txt";
string contentFile = String.Empty;
try
{
if (File.Exists(pathFile))
{
StreamReader sr = File.OpenText(pathFile);
contentFile = sr.ReadToEnd();
sr.Close();
// Print the content
Console.WriteLine(contentFile);
}
else
{
// Print the message
Console.WriteLine("It was not possible to find the file {0}", pathFile);
}
}
catch (Exception excp)
{
Console.WriteLine("Error:" + excp.ToString());
}
}
}
}
Result:
Programming in XML
Marc Vince
348
Programming
Programming in C#
Loren Gallipyos
234
Programming
Android
Norman Bert
419
Operating Systems
Linux
Hurth Francy
294
Operating Systems
WordPress
Milena Zarch
364
CMS
Joomla!
Denise Patrics
163
CMS
jQuery
Teresa Curtis
349
Programming
PS: Note: the title of the books and authors are invented and do not correspond to reality.