Monday, May 24, 2021

C# StreamReader Class

StreamReader class belongs to System.IO namespace and is used to read text from a file. The StreamReader class derives from TextReader and provides implementations of the members for reading from a stream. StreamReader is designed for characters reading from a byte stream in a particular encoding whereas classes derived from Stream are designed for byte input and output. 

The StreamReader class has non-static methods and properties and so, an instance of StreamReader class should be created to access its members. The Read and ReadLine methods of StreamReader class have many overloaded versions which are described at https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-5.0

using System;
using System.IO;
namespace ConsoleReaderStream
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"F:\Tasty.txt";
            using(FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(file))
                {
                    if (reader.Peek() > 0)
                    {
                        //Console.WriteLine(reader.ReadToEnd());//read till the end of line
                        string line = String.Empty;
                        while ((line = reader.ReadLine())!=null)
                        {
                            Console.WriteLine(line);
                        }
                        Console.WriteLine("Data read...");
                    }
                    else
                    {
                        Console.WriteLine("No data available to read from the file...");
                    }
                }
            }
            Console.ReadKey();
        }
    }
}

No comments:

Post a Comment

Hot Topics