C#. The Stream class. Stream search methods (operations)

The Stream class. Stream search methods (operations)

This topic is a continuation of the following topics:


Contents


Search other resources:




1. Property CanSeek. Example

The property is intended to determine if the current stream supports moving (rewinding) the file read/write pointer. According to the C# documentation, the general form of the property is as follows

public abstract bool CanSeek { get; }

Example. In the most generalized case, the process of rewinding a pointer using the Seek() method looks like this

...

using (FileStream fs = new FileStream("myfile.bin", ...))
{
  if (fs.CanSeek)
  {
    // Rewinding the pointer in the Seek() method
    fs.Seek(...);

    ...
  }
  else
  {
    Console.WriteLine(@"The stream doesn't support seeking.");
  }

  ...

}

 

2. Property Position. Example

If this property is overridden in a derived class, you can use it to:

  • read the current value of the file read/write pointer;
  • set a new value for the read/write pointer.

Example. The code snippet sets a new value for the file read pointer.

...

using (FileStream fWrite = new FileStream("myfile.bin", FileMode.Create, FileAccess.Write))
{
  ...

  // Set the pointer to the end of the file - for the last byte in the file
  fWrite.Position = fWrite.Length;

  // Set pointer to the beginning of the file
  fWrite.Position = 0;

  ...
}

...

 

3. The SetLength() method. Example

If a method is overridden in a subclass, then this method sets the length of the current stream. The general form of the method is as follows:

public abstract void SetLength(long value)

here value – a value that determines the size of the stream in bytes.

To set a new file (stream) size, the file must be writeable.

Example. Suppose you want to set the size of a byte file to 5000 bytes. To do this, you need to use the call:

...

using (FileStream fWrite = new FileStream("myfile.bin", FileMode.Create, FileAccess.Write))
{
  ...

  // Set the file size of 5000 bytes
  fWrite.SetLength(5000);

  ...
}

...

 

4. The Length property. Example

The Length property is used to determine the length of the file.

public abstract long Length { get; }

This property is useful when you need to allocate memory for a byte[] byte buffer.

Example. Suppose you need to read a line from a file that was previously written. The length of the string is unknown. The code snippet that solves this problem using the Length property. Here you need to keep in mind that only one line is written in the file.

...

// Reading a line from a file
using (FileStream fRead = new FileStream("myfile.bin", FileMode.Open, FileAccess.Read))
{
  // The string to be received from the file
  string str = "";

  // The buffer where the string will be written
  byte[] strByte;

  // Allocate memory for the buffer - use the Length property
  strByte = new byte[fRead.Length];

  // Read bytes from file into strByte buffer
  int bt;

  for (int i = 0; i < fRead.Length; i++)
  {
    bt = fRead.ReadByte(); // read byte from file
    str = str + (char)bt; // Append bt character to string
  }

  // Display the string
  Console.WriteLine("str = " + str);
}
...

 

5. The Seek() method. Example

The Seek() method rewinds the file read/write pointer by the specified number of bytes. According to the documentation, the general form of the Seek() method is as follows

public abstract long Seek(long offset, System.IO.SeekOrigin origin)

here

  • offset – offset in bytes to which you want to rewind the pointer;
  • origin – the position from which to start performing the offset. This position is determined by the SeekOrigin enumeration.

The SeekOrigin enumeration has the following constants:

  • Begin – defines the beginning of the stream;
  • Current – defines the current value of the pointer in the stream. Pointer movement (rewind, shift) occurs from the current position;
  • End – the end of the stream. The pointer moves from the end of the stream.

Example. In the example, three numbers of type double are written to the file. Then the second and third numbers are replaced with new values. The example also demonstrates the capabilities of the BitConverter class.

using System;
using System.IO;

namespace ConsoleApp10
{
  class Program
  {
    static void Main(string[] args)
    {
      // Writing three doubles to a file and overwriting the second
      using (FileStream fWrite = new FileStream("myfile.bin", FileMode.Create, FileAccess.Write))
      {
        // given 3 numbers of type double
        double x1 = 2.88;
        double x2 = 1.77;
        double x3 = -220.345;

        // an array of bytes that will be directly written to the file
        byte[] AB = new byte[sizeof(double)]; // allocate memory for double size

        // write the number x1
        AB = BitConverter.GetBytes(x1);
        fWrite.Write(AB, 0, AB.Length); // write the number - Write() method

        // write the number x2
        AB = BitConverter.GetBytes(x2);
        fWrite.Write(AB, 0, AB.Length);

        // write the number x3
        AB = BitConverter.GetBytes(x3);
        fWrite.Write(AB, 0, AB.Length);

        // Overwrite the number x2 with a different value - use the Seek() method
        fWrite.Seek(sizeof(double), SeekOrigin.Begin); // shift 1 number from the beginning
        AB = BitConverter.GetBytes(55.78); // the number 55.78 will be new instead of x2
        fWrite.Write(AB, 0, AB.Length);

        // Overwrite the number x3 with a different value - use an offset from the end of the file
        // Important: the offset value is negative.
        fWrite.Seek(-sizeof(double), SeekOrigin.End);
        AB = BitConverter.GetBytes(22.33);
        fWrite.Write(AB, 0, AB.Length);
      }

      // Reading a line from a file
      using (FileStream fRead = new FileStream("myfile.bin", FileMode.Open, FileAccess.Read))
      {
        // The numbers to be retrieved from the file
        double x1, x2, x3;

        // The buffer where the numbers will be written
        byte[] array = new byte[fRead.Length];

        // Read bytes from file into array buffer
        fRead.Read(array, 0, array.Length);

        // Get the first number from the buffer
        x1 = BitConverter.ToDouble(array, 0);

        // Get the second number from the buffer
        x2 = BitConverter.ToDouble(array, sizeof(double));

        // Get the third number from the buffer
        x3 = BitConverter.ToDouble(array, 2 * sizeof(double));

        // Display numbers
        Console.WriteLine("x1 = {0:f}", x1);
        Console.WriteLine("x2 = {0:f}", x2);
        Console.WriteLine("x3 = {0:f}", x3);
      }
    }
  }
}

Program execution result

x1 = 2.88
x2 = 55.78
x3 = 22.33

 


Related topics