views:

74

answers:

1

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?

+5  A: 

This particular version of IOException is thrown when the error code returned from the Win32 native function is ERROR_SHARING_VIOLATION (Documentation). It has the numeric value of 0x20 but is actually stored as 0x80070020 on the HRESULT property of the exception (it's the result of calling MakeHRFromErrorCode).

So the programatic way of checking for a sharing violation is checking the HResult property on the IOException for the value 0x80070020.

public static bool IsSharingViolation(this IOException ex) {
  return 0x80070020 == Marshal.GetHRForException(ex);
}

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.

JaredPar
Why not use the `ex.HResult` directly instead of `Marshal.GetHRForException`?
Anders Abel
@Anders because the HResult property has an accessibility level of protected so it's not generally accessible.
JaredPar
Fantastic answer JaredPar, thanks... In answer to your question; I need to detect this scenario because I need a friendly message for the presentation layer - it's ok if the conflict might not exist the moment after, due to the nature of my app... thanks again
Paul Killick