ZetCode

C# FileShare

last modified November 6, 2026

In this article we show how to use the FileShare enumeration in C#.

FileShare from the System.IO namespace controls what other streams may do with a file while we have it open. While FileAccess says what we want to do with the file, FileShare says what we allow others to do. The values are None, Read, Write, ReadWrite, Delete, and Inheritable.

On Windows, the sharing rules are enforced by the operating system for all programs. A file can be opened when both conditions hold:

A violation throws an IOException with the message "The process cannot access the file because it is being used by another process".

Linux and macOS have no such rules. .NET emulates only part of them with advisory locks: FileShare.None takes an exclusive lock and any other value a shared lock. As a result, only FileShare.None is enforced, and only against other .NET programs; programs that do not use the locks, such as text editors, are not affected.

The examples create a demo directory in the working directory and delete it at the end. The outputs come from Linux.

The enumeration values

FileShare is a flags enumeration.

Program.cs
foreach (FileShare share in Enum.GetValues<FileShare>())
{
    Console.WriteLine($"{share,-12} {(int)share}");
}

Console.WriteLine(FileShare.Read | FileShare.Delete);

We print the values and a combination of two of them.

Console.WriteLine(FileShare.Read | FileShare.Delete);

ReadWrite is the combination of Read and Write. Inheritable makes the file handle inheritable by child processes and is rarely needed.

$ dotnet run
None         0
Read         1
Write        2
ReadWrite    3
Delete       4
Inheritable  16
Read, Delete

Exclusive access

FileShare.None gives a stream exclusive access to the file. This works on all platforms.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "data.txt");
File.WriteAllText(path, "important data");

using (var owner = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
    try
    {
        using var other = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    }
    catch (IOException e)
    {
        Console.WriteLine($"{e.GetType().Name}: {e.Message.Replace(Environment.CurrentDirectory, ".")}");
    }

    try
    {
        File.ReadAllText(path);
    }
    catch (IOException)
    {
        Console.WriteLine("File.ReadAllText: IOException");
    }
}

Console.WriteLine($"after close: {File.ReadAllText(path)}");

Directory.Delete("demo", true);

While the first stream holds the file, we try to open it with another stream and with File.ReadAllText.

using (var owner = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))

The first stream allows no sharing.

using var other = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

The second stream asks only for reading and allows everything, but it fails because the first stream does not allow reading. The lock is held for the whole process, so even streams of the same program are refused.

$ dotnet run
IOException: The process cannot access the file './demo/data.txt' because it is being used by another process.
File.ReadAllText: IOException
after close: important data

Sharing rules on Linux

The next example shows which combinations succeed on Linux.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "data.txt");
File.WriteAllText(path, "data");

Test(FileAccess.Write, FileShare.Read, FileAccess.Read, FileShare.ReadWrite);
Test(FileAccess.Write, FileShare.Read, FileAccess.Read, FileShare.Read);
Test(FileAccess.Read, FileShare.Read, FileAccess.Write, FileShare.ReadWrite);
Test(FileAccess.Read, FileShare.ReadWrite, FileAccess.Read, FileShare.None);

Directory.Delete("demo", true);

void Test(FileAccess access1, FileShare share1, FileAccess access2, FileShare share2)
{
    using var first = new FileStream(path, FileMode.Open, access1, share1);
    string result;

    try
    {
        using var second = new FileStream(path, FileMode.Open, access2, share2);
        result = "opened";
    }
    catch (IOException)
    {
        result = "IOException";
    }

    Console.WriteLine($"{$"{access1}/{share1}",-16} then {$"{access2}/{share2}",-16} {result}");
}

For each pair, we open the file with the first access and share mode and then with the second.

Test(FileAccess.Write, FileShare.Read, FileAccess.Read, FileShare.Read);

The first stream writes and allows reading. The second stream reads, but it allows only reading. On Windows this fails, because the second stream would not allow the write access that the first already has. On Linux it succeeds.

Test(FileAccess.Read, FileShare.Read, FileAccess.Write, FileShare.ReadWrite);

The first stream allows only reading, so on Windows the second stream cannot open the file for writing. On Linux it can.

Test(FileAccess.Read, FileShare.ReadWrite, FileAccess.Read, FileShare.None);

A request for exclusive access fails on every platform while another stream has the file open. Code that must run on several systems should not depend on the sharing rules for correctness, apart from FileShare.None.

$ dotnet run
Write/Read       then Read/ReadWrite   opened
Write/Read       then Read/Read        opened
Read/Read        then Write/ReadWrite  opened
Read/ReadWrite   then Read/None        IOException

Reading a file while it is written

A common task is to read a log file that another program is writing. The reader has to allow writing, otherwise it collides with the writer on Windows.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "app.log");

using (var writerStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
using (var writer = new StreamWriter(writerStream) { AutoFlush = true })
using (var readerStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(readerStream))
{
    for (int i = 1; i <= 3; i++)
    {
        writer.WriteLine($"event {i}");

        string? line;
        while ((line = reader.ReadLine()) != null)
        {
            Console.WriteLine($"read: {line}");
        }
    }
}

Directory.Delete("demo", true);

One stream writes lines and another stream reads them as they appear.

using (var writerStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))

The writer allows others to read.

using (var readerStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))

The reader asks for read access and allows reading and writing, which includes the writer that already has the file open. File.ReadAllText and File.OpenRead use FileShare.Read, so on Windows they fail on a file that another program has open for writing.

while ((line = reader.ReadLine()) != null)

ReadLine returns null when it reaches the current end of the file. After the writer adds a line, the next call returns it. The AutoFlush property of the writer makes each line reach the file at once.

$ dotnet run
read: event 1
read: event 2
read: event 3

Renaming and deleting an open file

FileShare.Delete allows others to rename or delete the file while it is open.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "report.txt");
File.WriteAllText(path, "report content");

using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete))
{
    File.Move(path, Path.Combine("demo", "report-old.txt"));
    Console.WriteLine($"renamed while open: {File.Exists(path)}");

    File.Delete(Path.Combine("demo", "report-old.txt"));
    Console.WriteLine($"files left: {Directory.GetFiles("demo").Length}");

    using var reader = new StreamReader(fs);
    Console.WriteLine($"still readable: {reader.ReadToEnd()}");
}

Directory.Delete("demo", true);

We rename and delete a file while a stream still has it open, then read the content through the stream.

using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete))

Without the Delete flag, the move and the delete fail on Windows. On Linux, they always succeed, whatever the share mode.

Console.WriteLine($"still readable: {reader.ReadToEnd()}");

The file has no name in the directory any more, but the open stream still reads its data. The data is released when the last stream is closed.

$ dotnet run
renamed while open: False
files left: 0
still readable: report content

Retrying when a file is locked

When another program holds a file exclusively, waiting a moment and trying again often helps, for example with a file that is still being copied.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "shared.txt");
File.WriteAllText(path, "ready");

var locker = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
_ = Task.Delay(350).ContinueWith(_ => locker.Dispose());

using (FileStream fs = OpenWithRetry(path, attempts: 10, delay: TimeSpan.FromMilliseconds(100)))
using (var reader = new StreamReader(fs))
{
    Console.WriteLine(reader.ReadToEnd());
}

Directory.Delete("demo", true);

static FileStream OpenWithRetry(string path, int attempts, TimeSpan delay)
{
    for (int i = 1; ; i++)
    {
        try
        {
            return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
        }
        catch (IOException) when (i < attempts && File.Exists(path))
        {
            Console.WriteLine($"attempt {i}: file is locked");
            Thread.Sleep(delay);
        }
    }
}

A stream locks the file and a task releases it after 350 milliseconds. Meanwhile we try to open the file.

catch (IOException) when (i < attempts && File.Exists(path))

The exception filter catches the error only while attempts remain and the file exists, so a missing file or the last failed attempt is passed to the caller. The sharing violation is a plain IOException; on Windows its HResult is 0x80070020 (ERROR_SHARING_VIOLATION), which can be used to tell it from other I/O errors.

Thread.Sleep(delay);

Between attempts we wait 100 milliseconds. Asynchronous code would use await Task.Delay instead.

$ dotnet run
attempt 1: file is locked
attempt 2: file is locked
attempt 3: file is locked
attempt 4: file is locked
ready

Source

FileShare enum

In this article we have worked with the FileShare enumeration in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.