.NET Documentation

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

NameTypeDescription
CanReadboolIndicates whether the current stream supports reading.
CanSeekboolIndicates whether the current stream supports seeking.
CanWriteboolIndicates whether the current stream supports writing.
LengthlongGets the length in bytes of the stream.
PositionlongGets or sets the current position within the stream.

Methods

NameSignatureDescription
Readint Read(byte[] buffer, int offset, int count)Reads a block of bytes from the stream and writes the data to a buffer.
Writevoid Write(byte[] buffer, int offset, int count)Writes a block of bytes to the stream from a buffer.
Seeklong Seek(long offset, SeekOrigin origin)Sets the position within the current stream.
Flushvoid Flush()Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
CopyToAsyncTask CopyToAsync(Stream destination, int bufferSize = 81920, CancellationToken cancellationToken = default)Asynchronously reads the bytes from the current stream and writes them to another stream.
Disposevoid 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.