System.IO.Stream Class
The System.IO.Stream abstract class provides a generic view of a sequence of bytes, supporting reading, writing, and seeking operations.
Overview
Properties
Methods
Examples
Namespace
System.IO
Assembly
System.Runtime.dll
Base Class
object
Derived Types
Properties
| Name | Type | Description |
|---|---|---|
CanRead | bool | Indicates whether the current stream supports reading. |
CanSeek | bool | Indicates whether the current stream supports seeking. |
CanWrite | bool | Indicates whether the current stream supports writing. |
Length | long | Gets the length in bytes of the stream. |
Position | long | Gets or sets the current position within the stream. |
Methods
| Name | Signature | Description |
|---|---|---|
Read | int Read(byte[] buffer, int offset, int count) | Reads a block of bytes from the stream and writes the data to a buffer. |
Write | void Write(byte[] buffer, int offset, int count) | Writes a block of bytes to the stream from a buffer. |
Seek | long Seek(long offset, SeekOrigin origin) | Sets the position within the current stream. |
Flush | void Flush() | Clears all buffers for the current writer and causes any buffered data to be written to the underlying device. |
CopyToAsync | Task CopyToAsync(Stream destination, int bufferSize = 81920, CancellationToken cancellationToken = default) | Asynchronously reads the bytes from the current stream and writes them to another stream. |
Dispose | void Dispose() | Releases the unmanaged resources used by the Stream and optionally releases the managed resources. |
Example: Copying a file using Stream
using System;
using System.IO;
class Program
{
static void Main()
{
using var source = new FileStream("source.bin", FileMode.Open, FileAccess.Read);
using var destination = new FileStream("dest.bin", FileMode.Create, FileAccess.Write);
source.CopyTo(destination);
Console.WriteLine("Copy completed.");
}
}
For more advanced scenarios see the Asynchronous Streaming guide.