When I open a file, I want to know if it is being used by another process so I can perform special handling; any other IOException I will bubble up. An IOException’s Message property contains “The process cannot access the file ‘foo’ because it is being used by another process.”, but this is unsuitable for programmatic detection. What is the safest, most robust way to detect a file being used by another process?
Share
This particular version of
IOExceptionis thrown when the error code returned from the Win32 native function isERROR_SHARING_VIOLATION(Documentation). It has the numeric value of0x20but is actually stored as0x80070020on theHRESULTproperty of the exception (it’s the result of calling MakeHRFromErrorCode).So the programatic way of checking for a sharing violation is checking the
HResultproperty on theIOExceptionfor the value0x80070020.However I do question what exactly you want to do in the scenario that it was thrown as the result of a sharing violation. The moment the exception is thrown the other process could exit and hence remove the violation.