FileStream Class

System.IO.FileStream provides a Stream for a file, supporting both synchronous and asynchronous read/write operations.

Namespace

System.IO

Assembly

System.IO.FileSystem.dll

Syntax

public sealed class FileStream : Stream

Constructors

public FileStream(string path, FileMode mode);
public FileStream(string path, FileMode mode, FileAccess access);
public FileStream(string path, FileMode mode, FileAccess access, FileShare share);
public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize);
public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync);

Properties

bool CanRead { get; }
bool CanWrite { get; }
bool CanSeek { get; }
long Length { get; }
long Position { get; set; }
bool IsAsync { get; }

Methods

void Flush();
Task FlushAsync(CancellationToken cancellationToken = default);
int Read(byte[] buffer, int offset, int count);
Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default);
void Write(byte[] buffer, int offset, int count);
Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default);
long Seek(long offset, SeekOrigin origin);
void SetLength(long value);
void Close();

Example

// Write text to a file using FileStream
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        string content = "Hello, FileStream!";

        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            fs.Write(bytes, 0, bytes.Length);
        }

        Console.WriteLine($"File '{path}' created.");
    }
}

See Also