C#. Methods of StreamReader class




Methods of StreamReader class

This topic is a continuation of the topic:


Contents


Search other websites:

1. Connecting the System.IO namespace

In all of the following examples, in order to use the methods, you must first include the System and System.IO namespaces.

using System;
using System.IO;

...

 

2. Methods of StreamReader class
2.1. Methods Close() and Dispose()

According to the documentation, the Close() and Dispose() methods have the following general form:

public override void Close();
protected override void Dispose(bool disposing);

The Close() method closes the StreamReader and the underlying stream and releases any system resources associated with this object.

The Dispose() method closes the underlying stream, releases unmanaged resources, and optionally releases managed resources using the disposing parameter. If disposing = true, then both managed and unmanaged resources are released. If disposing = false, then only unmanaged resources are released.

Call the Dispose() method with a parameter will fail because it is declared protected. The TextReader class has a parameterless variant of the Dispose() method that the StreamReader class inherits. This method has declarations

void TextReader.Dispose();

and can be called from an instance of type StreamReader.

Using the Close() method looks like this

...

StreamReader fIn = new StreamReader("myfile1.txt");

fIn.Close();

...

The Dispose() method can be called similarly.

fIn.Dispose();

 

2.2. Method Peek()

The Peek() method is used when you need to predetermine the next character to be read from the stream. The method returns the next character of the stream, but does not move the read pointer from the file. The method returns the next character of the stream, but does not move the read pointer from the file.

public override int Peek();

The method returns an integer representing the next character. If there are no characters in the stream or the stream does not support searching, then the method returns -1.

Example. The example uses the Peek() method to check if the end of the file has been reached. The contents of the file myfile1.txt are displayed on the screen.

...

// Declare an instance of the StreamReader class
using (StreamReader fIn = new StreamReader("myfile1.txt"))
{
  // Method Peek() - determine if the end of the file
  while (fIn.Peek() != -1)
  {
    string s = fIn.ReadLine(); // read a line
    Console.WriteLine(s); // print a string to the screen
  }

  fIn.Close();
}

...

 

2.3. Method Read(). Reading a single character

To read a character from the input stream, the Read() method is used, which has the following declaration

public override int Read();

This method reads the next character from the input stream and advances the file read pointer by one character. The method returns the character read, represented as type System.Int32, or -1 if the character could not be read. If the file does not exist, a System.IOException is thrown.

Example. In the example, using the Read() method, the file is read character by character and its contents are displayed on the screen.

using System;

// Include System.IO namespace
using System.IO;

namespace ConsoleApp12
{
  class Program
  {
    static void Main(string[] args)
    {
      // Read the contents of the file myfile1.txt and display it on the screen
      try
      {
        StreamReader fIn = new StreamReader("myfile1.txt");
        int c;

        while ((c = fIn.Read()) != -1)
        {
          Console.Write((char)c); // Display the character
        }

        fIn.Close();
      }
      catch (IOException e)
      {
        Console.WriteLine(e.Message);
      }
    }
  }
}

 

2.4. Method Read(char[], int, int). Reading a group of characters into a buffer

Another overloaded implementation of the Read() method is for reading a set of characters into the specified buffer and has the following declaration

public override int Read(char[] buffer, int index, int count);

here

  • buffer – a character array into which to read the contents of the current input stream. Stream characters are written at positions index to index + count-1 in the buffer array;
  • index – position in the buffer from which the reading is started;
  • count – maximum number of characters read.

The method returns the number of characters actually read. The value of the characters read ranges from 0 to count. If the characters could not be read, the method returns 0.

When using the method, the following exceptions are handled:

  • System.ArgumentException – the case when the length of buffer minus index is less than count;
  • System.ArgumentNullException – buffer is null;
  • System.ArgumentOutOfRangeExceptionindex or count is negative;
  • System.IO.IOException – the case when the stream is closed.

Example. The example reads a file in chunks of 10 characters using the Read() method.

using System;

// Include the System.IO namespace
using System.IO;

namespace ConsoleApp12
{
  class Program
  {
    static void TestMethod()
    {
      // Declare the instance of StreamWriter class
      using (StreamWriter fOut = new StreamWriter("myfile1.txt"))
      {
        // Write array of numbers to file as a string
        int[] A = { 22, 331, 32, 17, 19 };

        for (int i = 0; i < A.Length; i++)
        {
          // Write array element A to file
          fOut.Write("{0} ", A[i]);
        }

        // Add 2 more numbers in separate lines
        fOut.WriteLine();
        fOut.WriteLine(229);
        fOut.WriteLine(77);

        fOut.Close();
      }

      // Declare an instance of the StreamReader class
      using (StreamReader fIn = new StreamReader("myfile1.txt"))
      {
        // The Peek() method - determine if the end of the file
        while (fIn.Peek() != -1)
        {
          string s = fIn.ReadLine(); // read a string
          Console.WriteLine(s); // display string on the screen
        }

        fIn.Close();
      }
    }

    static void Main(string[] args)
    {
      // Read the contents of the file myfile1.txt and display it on the screen
      try
      {
        // Create an instance of type StreamReader
        StreamReader fIn = new StreamReader("myfile1.txt");

        // Create a fragment where data will be written
        char[] buffer = new char[10];
        int n; // Number of characters read from file

        do
        {
          // Read 10 characters from file fIn into buffer
          n = fIn.Read(buffer, 0, 10);

          // Print the buffer to the screen
          for (int i = 0; i < n; i++)
            Console.Write(buffer[i]);
        }
        while (n != 0); // checking if the end of the file

        fIn.Close();
      }
      catch (Exception e) // catch all exceptions
      {
        Console.WriteLine(e.Message);
      }
    }
  }
}

 

2.5. Method ReadBlock(). Read a character set from a file stream

The ReadBlock() method reads a set of characters from the input stream into the specified memory location. The method has the following declaration

public override int ReadBlock(char[] buffer, int index, int count);

here

  • buffer – array into which to read characters from the stream. In the array, characters are written from position index to position (index + count – 1);
  • index – the starting position in the array to which the characters are read from the stream;
  • count – the maximum number of characters to be read.

When using the method, exceptions of the following types can be thrown:

  • System.ArgumentException – the case when the length of buffer minus index is less than count;
  • System.ArgumentNullException – buffer is null;
  • System.ArgumentOutOfRangeExceptionindex or count is negative;
  • System.IO.IOException – the case when the stream is closed;
  • System.ObjectDisposedException – the case when the StreamReader is closed.

Example. The example reads the contents of a file into buffer at one time. The FileInfo class is used to determine the length of the file.

using System;

// Include System.IO namespace
using System.IO;

namespace ConsoleApp12
{
  class Program
  {
    static void Main(string[] args)
    {
      // Read the contents of the file myfile1.txt and display it on the screen
      try
      {
        // Create the instance of StreamReader class
        StreamReader fIn = new StreamReader("myfile1.txt");

        // Determine file length
        FileInfo fInfo = new FileInfo("myfile1.txt");
        long len = fInfo.Length;

        // buffer for data, buffer size is equal to file length
        char[] buffer = new char[len];

        // Read data from the file at one time
        fIn.ReadBlock(buffer, 0, buffer.Length);

        // Display the contents of the file on the screen
        Console.Write(buffer);

        fIn.Close();
      }
      catch (Exception e)
      {
        Console.WriteLine(e.Message);
      }
    }
  }
}

 

2.6. Method ReadLine(). Read the string

The ReadLine() method is used to read a line from a file stream. According to the documentation, the method has the following declaration

public override string ReadLine();

The method returns a character string from the current file stream. If the end of the stream is reached, the method returns null.

When using the method, exceptions of the following types can be thrown:

  • System.OutOfMemoryException – the case when there is not enough memory to allocate it to the returned string;
  • System.IO.IOException – I/O error.

Example. The example reads a text file line by line and displays it on the screen.

using System;

// Include the System.IO namespace
using System.IO;

namespace ConsoleApp12
{
  class Program
  {
    static void Main(string[] args)
    {
      // Read the contents of the file myfile1.txt and display it on the screen
      try
      {
        // Create the instance of StreamReader type
        StreamReader fIn = new StreamReader("myfile1.txt");

        // Reading a file line by line
        string s;

        do
        {
          // Read the string
          s = fIn.ReadLine();

          // Display the string
          Console.WriteLine(s);
        }
        while (s != null); // checking if the end of the file

        fIn.Close();
      }
      catch (OutOfMemoryException e)
      {
        Console.WriteLine(e.Message);
      }
      catch (System.IO.IOException e)
      {
        Console.WriteLine(e.Message);
      }
    }
  }
}

 

2.7. Method ReadToEnd()

The ReadToEnd() method reads all characters from the current read position to the end of the stream. The method declaration is as follows

public override string ReadToEnd();

The method returns a stream as a string. If the current position points to the end of the stream, the method returns an empty string “”.

When using the method, exceptions of the following types can be thrown:

  • System.OutOfMemoryException – the case when there is not enough memory to allocate it for the allocated string;
  • System.IO.IOException – I/O error.

Example. The example displays the contents of a text file to the screen. The file is read into a string by the ReadToEnd() method.

using System;

// Include the System.IO namespace
using System.IO;

namespace ConsoleApp12
{
  class Program
  {
    static void Main(string[] args)
    {
      try
      {
        // Create the instance of StreamReader type
        StreamReader fIn = new StreamReader("myfile1.txt");

        string buffer;

        // Read file as a string
        buffer = fIn.ReadToEnd();

        // Display string on the screen
        Console.Write(buffer);

        fIn.Close();
      }
      catch (OutOfMemoryException e)
      {
        Console.WriteLine(e.Message);
      }
      catch (System.IO.IOException e)
      {
        Console.WriteLine(e.Message);
      }
    }
  }
}

 

3. The properties of StreamReader class
3.1. Property BaseStream. Get a reference to the underlying stream

You can use the BaseStream property to get a reference to the underlying Stream. The property declaration is as follows

public virtual System.IO.Stream BaseStream { get; }

Example. The example determines the file size in bytes using a reference to the underlying stream.

using System;

// Include the System.IO namespace
using System.IO;

namespace ConsoleApp12
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create the instance of StreamReader type
      StreamReader fIn = new StreamReader("myfile1.txt");

      // Get a reference to base stream
      Stream stream = fIn.BaseStream;

      // Get the file size using reference
      long len = stream.Length;

      // Display the result
      Console.WriteLine("The size of file = {0}", len);

      // Close the stream
      fIn.Close();
    }
  }
}

 

3.2. Property CurrentEncoding. Get the stream encoding

The CurrentEncoding property allows you to get an object containing data about the current encoding in the stream. The property declaration is as follows:

public virtual System.Text.Encoding CurrentEncoding { get; }

To use the property, you can write something like the following code

...

// Create an instance of StreamReader type
StreamReader fIn = new StreamReader("myfile1.txt");

// Get the current encoding
System.Text.Encoding encoding = fIn.CurrentEncoding;

// ...

fIn.Close();

...

 

3.3. Property EndOfStream. Determine the end of the stream

The EndOfStream property is used to determine if the current stream position points to the end of the stream. The property declaration looks like

public bool EndOfStream { get; }

The property returns true if the current position of the stream indicates the end of the stream. Otherwise, the property returns false.

Using the property may throw a System.ObjectDisposedException exception.

Example. The example reads from a file character by character until the end of the file is reached. The end of the file is determined using the EndOfStream property.

using System;

// Include the System.IO namespace
using System.IO;

namespace ConsoleApp12
{
  class Program
  {
    static void Main(string[] args)
    {
      try
      {
        // Create the instance of StreamReader class
        StreamReader fIn = new StreamReader("myfile1.txt");

        Stream stream = fIn.BaseStream;

        System.Text.Encoding encoding = fIn.CurrentEncoding;

        char c;

        // A cycle of reading from a file character by character
        while (!fIn.EndOfStream) // checking the fact of the end of the file
        {
          c = (char)fIn.Read();
          Console.Write(c);
        }

        fIn.Close();
      }
      catch (ObjectDisposedException e)
      {
        Console.WriteLine(e.Message);
      }
    }
  }
}

 


Related topics