
15. Stream
Streams in C#
A stream represents a sequence of bytes that can be used to read and/or write data to storage media (files, memory, network connections, etc.). Unlike a container that permanently holds data, a stream is more like a conduit or pipeline through which data flows.
Key Characteristics
- No Permanent Storage
A stream by itself does not store data persistently. Instead, it reads from or writes to an underlying data source or sink (e.g., a file, memory buffer, or network socket).
- Sequential Access
Streams generally operate in a sequential manner, meaning you read or write data one portion at a time. You can sometimes seek to a specific position if the underlying stream supports it, but this depends on the capabilities of the source (for instance,
FileStream
supports seeking, butNetworkStream
does not).
- Abstract Base Class
In .NET,
System.IO.Stream
is an abstract class. Specific classes derive from it, such as:- FileStream (for reading/writing files)
- MemoryStream (for in-memory data)
- NetworkStream (for network operations)
Basic Operations
Streams typically support three basic operations:
- Read: Extract data from the stream into a buffer.
- Write: Send data from a buffer to the stream.
- Seek: Move to a specific position in the stream (only if
CanSeek
istrue
).
Example of reading a file using a FileStream
:
using (FileStream fs = new FileStream("example.txt", FileMode.Open))
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
// Process the data in buffer
}
}
Stream Types
- FileStream: For file I/O operations.
- MemoryStream: For data stored directly in memory (useful for temporary, in-memory processing).
- NetworkStream: For reading from and writing to network connections.
- CryptoStream: For encrypting/decrypting data passing through another stream.
- BufferedStream: For improving read/write performance on another stream by buffering data in memory.
Streams vs. Containers
A container (like a List<T>
or File
on disk) permanently holds data. A stream, by contrast, is a transient mechanism for moving data. Data goes in or out, but the stream itself doesn’t inherently store it. This flexibility allows you to plug different sources/sinks behind a consistent API.
Reference
The content in this document is based on the original notes provided in Azerbaijani. For further details, you can refer to the original document using the following link:
Original Note - Azerbaijani Version