To open a file with exclusive access in C#, you can use the
FileStream constructor and explicitly set the FileShare mode to
None.
Example: Open a file with exclusive access
using System;
using System.IO;
public class ExclusiveFileAccess
{
public static FileStream OpenExclusive(string path)
{
return new FileStream(
path,
FileMode.OpenOrCreate, // Open existing or create new
FileAccess.ReadWrite, // Allow reading and writing
FileShare.None // Do not allow any other access
);
}
}
FileShare.None means:
No other process or thread can open the file — not for reading, writing, or even deleting — until the stream is closed.
Usage
try
{
using var stream = ExclusiveFileAccess.OpenExclusive("data.txt");
using var writer = new StreamWriter(stream);
writer.WriteLine("This file is locked for exclusive access.");
}
catch (IOException ex)
{
Console.WriteLine("Could not access file exclusively: " + ex.Message);
}
Summary of FileShare Options
FileShare Option
Allows Other Processes To...
None
No access (exclusive)
Read
Read only
Write
Write only
ReadWrite
Read and write
Delete
Delete
Notes
Always use a using block or
Dispose() to release the lock promptly.
On Windows, if another process tries to open the file while you have it open with
FileShare.None, it will throw an IOException.
On Linux, file locking behavior is advisory (not enforced by the OS unless using additional mechanisms like
fcntl).
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To open a file with exclusive access in C#, you can use the
FileStreamconstructor and explicitly set theFileSharemode toNone.Example: Open a file with exclusive access
FileShare.Nonemeans:No other process or thread can open the file — not for reading, writing, or even deleting — until the stream is closed.
Usage
Summary of
FileShareOptionsNoneReadWriteReadWriteDeleteNotes
usingblock orDispose()to release the lock promptly.FileShare.None, it will throw anIOException.fcntl).