How can you lock a file to prevent other processes from accessing it?
How can you lock a file to prevent other processes from accessing it?
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
Utpal Vishwas
20-May-2025To 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()