How do you safely access a file that may be locked by another process?
Ask by ICSM Computer
Updated 13 May 2025
To safely access a file that may be locked by another process in C#, you need to handle potential
IOExceptions orUnauthorizedAccessExceptions gracefully and try opening the file in read-only and shared mode when appropriate.1. Open File in Shared Read Mode
If you're only reading, you can allow shared access using
FileShare.ReadWrite.FileShare.ReadWriteallows other processes to keep the file open for reading or writing while your code reads from it.2. Retry Logic (for temporary locks)
Sometimes a file is locked only briefly (e.g., by an antivirus or another thread). You can retry:
3. Check If File Is Locked (Optional Heuristic)
There's no 100% reliable way to check if a file is locked without trying to open it, but this is a common pattern:
Notes:
FileShare.Noneunless you're sure no one else should access the file.FileShare.ReadWrite.