Stream Class

Represents a generic stream of bytes. This is an abstract class.

Overview

The Stream class is the abstract base class for all streams in the .NET Framework. A stream is a sequence of bytes, and a program uses a stream to read from or write to a storage medium. The stream can be accessed sequentially.

The Stream class and its derived classes (such as FileStream, MemoryStream, and NetworkStream) provide the fundamental building blocks for working with input and output operations in .NET.

Abstract Members

As an abstract class, Stream defines several members that must be implemented by derived classes:

Common Derived Classes

Several concrete classes inherit from Stream to provide specific I/O functionality:

Usage Examples

Reading from a File


using System;
using System.IO;

public class FileReadExample
{
    public static void Main(string[] args)
    {
        try
        {
            using (FileStream fs = new FileStream("example.txt", FileMode.Open, FileAccess.Read))
            using (StreamReader reader = new StreamReader(fs))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error: example.txt not found.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
            

Writing to a Memory Stream


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

public class MemoryWriteExample
{
    public static void Main(string[] args)
    {
        using (MemoryStream ms = new MemoryStream())
        using (StreamWriter writer = new StreamWriter(ms, Encoding.UTF8))
        {
            writer.WriteLine("Hello, Memory Stream!");
            writer.WriteLine("This is a test.");
            writer.Flush(); // Ensure all buffered data is written

            // To read from the memory stream after writing:
            ms.Position = 0; // Reset stream position to the beginning
            using (StreamReader reader = new StreamReader(ms))
            {
                string content = reader.ReadToEnd();
                Console.WriteLine("Content of Memory Stream:");
                Console.WriteLine(content);
            }
        }
    }
}
            

Thread Safety

Stream objects are not guaranteed to be thread-safe. If multiple threads will access the same stream instance, you must use synchronization mechanisms, such as locks, to protect the stream from concurrent access.

Disposing Streams

It is crucial to dispose of Stream objects when they are no longer needed. This releases any unmanaged resources held by the stream, such as file handles or network connections. The using statement is the recommended way to ensure streams are properly disposed of:


using (Stream myStream = GetStream())
{
    // Use myStream here
} // myStream is automatically disposed here