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:
CanRead
: Gets a value indicating whether the stream supports reading.CanSeek
: Gets a value indicating whether the stream supports seeking.CanTimeout
: Gets a value indicating whether the stream supports timeouts.Length
: Gets the length of the stream in bytes.Position
: Gets or sets the current position within the stream.Read(byte[] buffer, int offset, int count)
: Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.Seek(long offset, SeekOrigin origin)
: Sets the position within the current stream.SetLength(long value)
: Sets the length of the current stream.Write(byte[] buffer, int offset, int count)
: Writes a sequence of bytes to the current stream and advances the position within the stream by the number of bytes written.
Common Derived Classes
Several concrete classes inherit from Stream
to provide specific I/O functionality:
FileStream
: For reading from and writing to files.MemoryStream
: For reading from and writing to memory as a stream.NetworkStream
: For sending and receiving data over a network socket.BufferedStream
: Wraps another stream to add buffering capabilities.
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