C#. The Stream class. Review of methods

The Stream class. Review of methods. Methods for reading from a stream. Examples


Contents


Search other resources:




1. The Stream class. Stream operations

The base class for all streams is the abstract Stream class, which is defined in the System.IO namespace. The class provides a generic representation of all I/O streams. The programmer does not bother over separate operating system components and basic I/O devices.

The Stream class defines properties and methods that perform the following operations on a stream:

  • reading the stream;
  • writing the stream;
  • search in the stream;
  • closing the stream;
  • stream discharge;
  • timeout setting;
  • other operations.

 

2. Stream reading operations (methods)

The following methods and properties are defined for reading a stream:

  • CanRead property – defines the ability of the stream to support reading;
  • Read() method – reads a sequence of bytes from the current stream;
  • ReadByte() method – reads one byte from the current stream.

 

2.1. Property CanRead. General form. Example

The CanRead property used in the inherited class to determine whether the current stream supports reading. The general form of the property is as follows:

public abstract bool CanRead { get; }

If the property returns true, then the stream is readable.

Example. The example determines whether the file stream is readable.

using System;
using System.IO;

namespace ConsoleApp10
{
  class Program
  {
    static void Main(string[] args)
    {
      // 1. Create a stream and link it with the file "myfile.txt"
      Stream stream;

      using (stream = new FileStream("myfile.txt", FileMode.Create))
      {
        // 2. CanRead property - determine if the stream is readable
        if (stream.CanRead)
          Console.WriteLine("Stream supports reading.");
        else
          Console.WriteLine("Stream does not support reading.");

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

 

2.2. Method Read(). Example

Abstract method Read() is basic when you need to read a sequence of bytes from the current stream. The method has several implementations. The general form of the most common implementation of the method is as follows

public abstract int Read(byte[] buffer, int offset, int count)

here

  • buffer – an array of the specified size into which the stream data is read;
  • offset – offset (starting from 0) in buffer, from which data reading from the stream starts;
  • count is the maximum number of bytes that can be read from the current stream.

After reading, the position in the stream is shifted by the number of bytes read.

Example. In the example, an array of strings of type string[] is written to the file. This array of strings is then read by the Read() method.

using System;
using System.IO;
using System.Text;

namespace ConsoleApp10
{
  class Program
  {
    static void Main(string[] args)
    {
      // Write array of strings to file
      using (FileStream fw = new FileStream("strings.dat", FileMode.Create, FileAccess.Write))
      {
        // Original array of strings
        string[] AS = { "abcd", "defgh", "jklmn", "jprst" };
        byte[] AB;

        // First write the number of lines
        AB = BitConverter.GetBytes(AS.Length); // byte[] <= AS.Length
        fw.Write(AB, 0, AB.Length);

        // Write array of strings
        for (int i = 0; i < AS.Length; i++)
        {
          // first write the length of the string
          AB = BitConverter.GetBytes(AS[i].Length);
          fw.Write(AB, 0, AB.Length);

          // then write the string itself
          // byte[] <= string
          AB = Encoding.Default.GetBytes(AS[i]);
          fw.Write(AB, 0, AB.Length);
        }
      }

      // Read array of strings from file
      using (FileStream fr = new FileStream("strings.dat", FileMode.Open, FileAccess.Read))
      {
        // The resulting array
        string[] AS2;

        // Additional variables
        byte[] AB2;

        // Read number of lines
        AB2 = new byte[sizeof(int)];
        fr.Read(AB2, 0, AB2.Length); // read bytes from file
        int count = BitConverter.ToInt32(AB2, 0);
        int len;

        // Allocate memory for array of strings
        AS2 = new string[count];

        // Read lines in a loop
        for (int i = 0; i < AS2.Length; i++)
        {
          // First, read the length of the string in bytes
          AB2 = new byte[sizeof(int)];
          fr.Read(AB2, 0, AB2.Length);
          len = BitConverter.ToInt32(AB2, 0); // Get string length

          // Read a string len bytes long into buffer AB2
          AB2 = new byte[len]; // allocate memory for the buffer
          fr.Read(AB2, 0, len); // read length into buffer

          // string <= byte[]
          AS2[i] = "";
          for (int j = 0; j < AB2.Length; j++)
          {
            AS2[i] = AS2[i] + (char)AB2[j];
          }
        }

        // Display the array of strings
        for (int i = 0; i < AS2.Length; i++)
        {
          Console.WriteLine("{0}", AS2[i]);
        }
      }
    }
  }
}

The result of the program

abcd
defgh
jklmn
jprst

 

2.3. The ReadByte() method. Example

The ReadByte() method is used in the inherited classes to read a byte from a stream. After reading, the current read position is shifted by 1 byte. If end of file is reached, -1 is returned.

The general form of the method is as follows

public virtual int ReadByte()

Example. Write a number of type int and a number of type double to a file. Then read these numbers.

using System;
using System.IO;

namespace ConsoleApp10
{
  class Program
  {
    static void Main(string[] args)
    {
      // Writing numbers to a file
      using (FileStream fWrite = new FileStream("myfile.bin", FileMode.Create, FileAccess.Write))
      {
        // the numbers to be written
        int num1 = 23;
        double num2 = 3.88;

        // an array of bytes that will be directly written to the file
        byte[] numByte1 = BitConverter.GetBytes(num1);
        byte[] numByte2 = BitConverter.GetBytes(num2);

        // write numbers - Write() method
        fWrite.Write(numByte1, 0, numByte1.Length);
        fWrite.Write(numByte2, 0, numByte2.Length);
      }

      // Reading a line from a file
      using (FileStream fRead = new FileStream("myfile.bin", FileMode.Open, FileAccess.Read))
      {
        // The numbers that are read from the file
        int num1;
        double num2;

        // Arrays of bytes into which numbers from the file will be read
        byte[] numByte1 = new byte[sizeof(int)];
        byte[] numByte2 = new byte[sizeof(double)];

        // Read a number of type int - use the ReadByte() method
        for (int i = 0; i < numByte1.Length; i++)
          numByte1[i] = (byte)fRead.ReadByte();
        num1 = BitConverter.ToInt32(numByte1);
        Console.WriteLine("num1 = {0}", num1);

        // Read the number of double type
        for (int i = 0; i < numByte2.Length; i++)
          numByte2[i] = (byte)fRead.ReadByte();

        num2 = BitConverter.ToDouble(numByte2);
        Console.WriteLine("num2 = {0}", num2);
      }
    }
  }
}

The result of the program

num1 = 23
num2 = 3.88

 


Related topics