C#. The Stream class. Operations (methods) of writing to a file stream

The Stream class. Operations (methods) of writing to a file stream. Examples

This topic is a continuation of the topic:


Contents


Search other resources:




1. Stream write operations. A brief overview

The following properties and methods (operations) are used to write to a stream:

  • property CanWrite – defines the ability of the stream to write;
  • method Write() – writes a sequence of bytes to the current stream;
  • method WriteByte() – writes a byte to the current stream.

  

2. Property CanWrite. Example

You can use the CanWrite property to determine if the stream supports writing data. The general form of the property is as follows:

public abstract bool CanWrite { get; }

If the stream is writable, then the CanWrite property returns true. Otherwise, false is returned.

Example. The example creates a stream, which is associated with the file “myfile.txt”. It then uses the CanWrite property to determine if the stream supports writing.

using System;
using System.IO;

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

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

        // 3. Закрыть поток
        stream.Close();
      }
    }
  }
}

  

3. The Write() method. Example

The Write() method is designed to write a sequence of bytes to the current stream. The general form of the method is as follows:

public abstract void Write(byte[] buffer, int offset, int count);

here

  • buffer – an array of bytes that are copied to the current stream;
  • offset – offset in the buffer array from which to start copying bytes into the current stream;
  • count – the number of bytes to be written to the current stream.

Example. The example writes a two-dimensional array of type int[] to a binary file. Then this array is read from the file for control.

using System;
using System.IO;

namespace ConsoleApp10
{
  class Program
  {
    static void Main(string[] args)
    {
      // Write array of strings to file
      using (FileStream fw = new FileStream("integers.dat", FileMode.Create, FileAccess.Write))
      {
        // Original array of integers
        int[,] AI = { { 2, 3, 5},
                      { 1, 8, 7 },
                      { 4, 2, 3 },
                      { -1, -2, 0 }
                    };

        // Additional variables
        byte[] AB;

        // First, write the dimension of the array 3*4
        // The number of rows
        int rows = AI.GetLength(0);
        AB = BitConverter.GetBytes(rows);
        fw.Write(AB, 0, AB.Length);

        // The number of columns
        int columns = AI.Length / AI.GetLength(0);
        AB = BitConverter.GetBytes(columns);
        fw.Write(AB, 0, AB.Length);

        // Cycle for writing numbers
        for (int i = 0; i < rows; i++)
          for (int j = 0; j < columns; j++)
          {
            // Write the number AI[i, j]
            AB = BitConverter.GetBytes(AI[i, j]);
            fw.Write(AB, 0, AB.Length);
          }
      }

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

        // Additional variables
        int rows, columns;
        byte[] AB;

        // Read the number of rows
        AB = new byte[sizeof(int)];
        fr.Read(AB, 0, AB.Length);
        rows = BitConverter.ToInt32(AB, 0);

        // Read the number of columns
        AB = new byte[sizeof(int)];
        fr.Read(AB, 0, AB.Length);
        columns = BitConverter.ToInt32(AB, 0);

        // Allocate memory for array of references
        AI2 = new int[rows, columns];

        // Цикл чтения чисел типа int
        for (int i = 0; i < rows; i++)
          for (int j = 0; j < columns; j++)
          {
            fr.Read(AB, 0, AB.Length);
            AI2[i, j] = BitConverter.ToInt32(AB, 0);
          }

        // Display the result
        Console.WriteLine("rows = {0}, columns = {1}", rows, columns);

        for (int i = 0; i < rows; i++)
        {
          for (int j = 0; j < columns; j++)
          {
            Console.Write("{0} ", AI2[i, j]);
          }
          Console.WriteLine();
        }
      }
    }
  }
}

The result of the program

rows = 4, columns = 3
2 3 5
1 8 7
4 2 3
-1 -2 0

  

4. The WriteByte() method. Example

The WriteByte() method is designed to write to a stream (file) at the current position of one byte. According to the C# documentation, the general form of the WriteByte() method is as follows:

public virtual void WriteByte(byte value)

here value is the byte to write.

Example. The example combines the WriteByte() and ReadByte() methods. You need to write a string to a file using the WriteByte() method. This string is then read by the ReadByte() method.

using System;
using System.IO;

namespace ConsoleApp10
{
  class Program
  {
    static void Main(string[] args)
    {
      // Demonstration of a combination of the WriteByte() and ReadByte() methods
      using (FileStream fWrite = new FileStream("myfile.bin", FileMode.Create, FileAccess.Write))
      {
        // The line to write to the file
        string str = "bestprog.net";

        // The cycle of byte write - WriteByte() method
        foreach (char c in str)
          fWrite.WriteByte((byte)c);
      }

      // Reading a line from a file
      using (FileStream fRead = new FileStream("myfile.bin", FileMode.Open, FileAccess.Read))
      {
        // Additional variables
        string str2 = ""; // the resulting string
        int bt;

        // Cycle of byte reading from a file - the ReadByte() method
        while ((bt = fRead.ReadByte()) != -1)
          str2 += (char)bt; // add the read byte to the string as a character

        // Display the result
        Console.WriteLine(str2);
      }
    }
  }
}

  


Related topics