Check if a file is locked in Windows
Here is a small Windows-specific probe for an existing file: try opening it for exclusive reading, and distinguish a sharing violation from other failures. A general IOException does not prove that a file is locked; missing files, invalid paths and other I/O failures must not all become “locked.” This is an exclusive-open check, not a complete detector of byte-range or application-level locks. See IOException and FileShare.
public static bool HasSharingViolationOnExclusiveRead(FileInfo file)
{
try
{
using FileStream stream = file.Open(
FileMode.Open, FileAccess.Read, FileShare.None);
return false;
}
catch (IOException ex) when (ex.HResult == unchecked((int)0x80070020))
{
return true; // Windows ERROR_SHARING_VIOLATION (32)
}
}
The filter recognizes Windows error 32, ERROR_SHARING_VIOLATION, represented by .NET as 0x80070020. Other exceptions, including missing-file and permission failures, propagate to the caller. The result false means only that this particular open succeeded at that moment. Sources: Windows error codes and .NET Win32 exception mapping.
Use FileMode.Open so the probe does not create a missing file. The original OpenOrCreate requests creation when the file is absent, so it is not a side-effect-free existence test. A read-only open also does not establish that later writing will succeed. If creating or writing the file is the real goal, attempt that intended operation and handle its failure instead of relying on a preliminary check. See FileMode.
There is a race after the stream is disposed: another process can open the file before your next operation. If you need exclusive access for actual work, open the file with the required access mode and keep that stream open while doing the work. The probe itself briefly requests exclusive access.
It can also be useful to identify processes that have the file open. The original article linked to this community code example; it is retained here as a historical reference, not as validated code. Microsoft’s Sysinternals Handle can show open handles and their owning processes. It requires administrative privileges, and an open handle is not necessarily proof of the sharing conflict you are investigating. Do not forcibly close handles: Microsoft warns that this can destabilize applications or the system.