Categories

Tools

bitdefender

1&1 Web Hosting

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.

Posted in C# by MdmSoft

If our work has been of help, you can help us with a small donation...
Our programmers will thank you!



All information contained in this web site are the property of MdmSoft. The information is provided "as is", MdmSoft will not be liable for any misuse of the code contained in these pages, nor can it be for inaccuracies, grammatical errors or other factors that may have caused damage or lost earnings. MdmSoft is not responsible for the content of comments posted by users.
The examples in this area have the educational and demonstration purposes only, and may be copied only for your reference, but cannot be used for commercial purposes, or for any other purpose, without the express written consent of MdmSoft.
MdmSoft also reserves the right to change, without notice, to your liking this web site, the pages and its sections, and may suspend temporarily or definitely the various services included on this site.
While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy.