Understanding C# Streams: A Comprehensive Guide

Understanding C# Streams: A Comprehensive Guide

Table of Contents

  1. What is a Stream?
  2. The Sequence of Bytes
  3. Stream Constructor
  4. Properties and Methods of the Stream Class
  5. Stream Examples
  6. Asynchronous Read and Write
  7. FIG Stream Class and its Subclasses
  8. Conclusion

What is a Stream?

A stream is a sequence of bytes that can be read from or written to a source, such as a file, network connection, or memory buffer. It provides a general view of a sequence of bytes, making it a fundamental concept in C# programming.

The Sequence of Bytes

The sequence of bytes is a continuous sequence of bytes, sorted in a specific order. This sequence can be thought of as a river, where each byte is like a fish swimming across the river. The stream is the river, and the bytes are the fish.

Stream Constructor

The Stream class has a protected constructor, but it is an abstract class and cannot be directly instantiated. To use a stream, you must create a custom class that inherits from the Stream class and overrides its properties and methods.

Properties and Methods of the Stream Class

The Stream class has several important properties and methods, including:

  1. CanRead: A read-only attribute that determines whether the stream can be read.
  2. CanSeek: A read-only attribute that determines whether the stream supports seeking.
  3. CanWrite: A read-only attribute that determines whether the stream is writable.
  4. Flush: A method that clears the buffer and writes the data to the underlying stream.
  5. Length: A property that indicates the length of the stream.
  6. Position: A property that indicates the current position in the stream.
  7. Read: A method that reads data from the stream into a buffer.
  8. Seek: A method that sets the position in the stream.
  9. Write: A method that writes data to the stream.
  10. Close: A method that closes the stream and releases resources.

Stream Examples

Here is an example of using the Stream class to read and write data:

static void Main(string[] args)
{
    byte[] buffer = null;
    string testString = "! Stream Hello world";
    char[] readCharArray = null;
    byte[] readBuffer = null;
    string readString = string.Empty;

    using (MemoryStream stream = new MemoryStream())
    {
        Console.WriteLine("Initial string is: {0}", testString);

        if (stream.CanWrite)
        {
            buffer = Encoding.Default.GetBytes(testString);
            stream.Write(buffer, 0, 3);
            Console.WriteLine("Now Stream.Position is at position {0}", stream.Position + 1);

            long newPositionInStream = stream.CanSeek ? stream.Seek(3, SeekOrigin.Current) : 0;
            Console.WriteLine("Repositioning Stream.Position to position {0}", newPositionInStream + 1);

            if (newPositionInStream < buffer.Length)
            {
                stream.Write(buffer, (int)newPositionInStream, buffer.Length - newPositionInStream);
            }

            stream.Position = 0;
            readBuffer = new byte[stream.Length];
            int count = stream.CanRead ? stream.Read(readBuffer, 0, readBuffer.Length) : 0;

            readBuffer = Encoding.Default.GetBytes(readBuffer);
            readCharArray = new char[Encoding.Default.GetCharCount(readBuffer, 0, count)];
            Encoding.Default.GetDecoder().GetChars(readBuffer, 0, count, readCharArray, 0);

            for (int i = 0; i < readCharArray.Length; i++)
            {
                readString += readCharArray[i];
            }

            Console.WriteLine("Read character string is: {0}", readString);
        }

        stream.Close();
    }
}

Asynchronous Read and Write

The Stream class has several methods that support asynchronous read and write operations, including BeginRead, BeginWrite, EndRead, and EndWrite.

FIG Stream Class and its Subclasses

The FIG Stream class and its subclasses are used to implement streams in C#. The main subclasses are FileStream, MemoryStream, and BufferedStream.

Conclusion

In this chapter, we have discussed the basics of streams in C#, including the sequence of bytes, stream constructor, properties and methods of the Stream class, stream examples, asynchronous read and write, and the FIG Stream class and its subclasses. We have also provided an example of using the Stream class to read and write data.