Stream Class

Namespace: System.IO

Represents a base class for all streams. A stream is an abstraction of a sequence of bytes, such as a file, an input socket, or a pipe. The system uses streams to read from and write to various data sources and sinks.

Inheritance: Object > Stream

Derived classes: MemoryStream, FileStream, BufferedStream, etc.

Public Constructors

The Stream class has no public constructors. It is an abstract class.

Public Properties

Public Methods

Protected Methods

Example Usage

Here's a simple example demonstrating how to write to and read from a MemoryStream:


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

public class Example
{
    public static void Main()
    {
        // Create a MemoryStream
        using (MemoryStream ms = new MemoryStream())
        {
            // Write some bytes to the stream
            byte[] dataToWrite = Encoding.UTF8.GetBytes("Hello, Stream!");
            ms.Write(dataToWrite, 0, dataToWrite.Length);

            // Ensure all data is written
            ms.Flush();

            // Reset the stream position to the beginning to read
            ms.Position = 0;

            // Read bytes from the stream
            byte[] buffer = new byte[ms.Length];
            int bytesRead = ms.Read(buffer, 0, buffer.Length);

            // Convert the bytes back to a string
            string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine($"Content read from stream: {content}");
        }
    }
}