To lock a file and prevent other processes from accessing it in C#, you can use the
FileStream class with appropriate FileShare settings. This ensures
exclusive access to the file while it's in use.
Locking a File with FileStream
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
// Open file with exclusive lock
using (FileStream fs = new FileStream(
filePath,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None)) // <-- Prevents other processes from accessing
{
Console.WriteLine("File is locked. Press Enter to release...");
Console.ReadLine(); // Keep the file locked until user input
}
Console.WriteLine("File is released.");
}
}
Key Parameters:
FileAccess.ReadWrite → Allows both reading and writing.
FileShare.None → Denies all other processes access to the file. (Other options include FileShare.Read, FileShare.Write, etc.)
Notes:
While the file is locked:
Any other process that tries to access it will throw an IOException.
The lock is automatically released when the FileStream is closed or disposed (e.g., at the end of
using).
Alternative: Lock() Method for Byte Ranges
If you only need to lock a specific portion of a file:
fs.Lock(0, fs.Length); // Lock the entire file (byte range)
And unlock with:
fs.Unlock(0, fs.Length);
This locks the file at the OS level, but not all APIs or platforms respect this lock, so
FileShare.None is more reliable for exclusive access.
Summary
Technique
Locks Entire File
Notes
FileStream + FileShare.None
Yes
Most reliable way to prevent access
fs.Lock() / fs.Unlock()
by range
Byte-range level locking (less common)
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 lock a file and prevent other processes from accessing it in C#, you can use the
FileStreamclass with appropriateFileSharesettings. This ensures exclusive access to the file while it's in use.Locking a File with
FileStreamKey Parameters:
FileAccess.ReadWrite→ Allows both reading and writing.FileShare.None→ Denies all other processes access to the file.(Other options include
FileShare.Read,FileShare.Write, etc.)Notes:
IOException.FileStreamis closed or disposed (e.g., at the end ofusing).Alternative:
Lock()Method for Byte RangesIf you only need to lock a specific portion of a file:
And unlock with:
Summary
FileStream + FileShare.Nonefs.Lock()/fs.Unlock()