As pointed out in other answers, you need to get HResult errors and check it out. HResult of 32 is a violation of sharing.
In .NET 4.5, an IOException has the public HResult property, so you can simply do the following:
try { // do file IO here } catch (IOException e) { if (e.HResult == 32) // 32 = Sharing violation { // Recovery logic goes here } else { throw; // didn't need to catch this } }
In earlier versions of .NET, you need to get HResult by calling Marshal.GetHRForException(Exception) , so similar code would look like this:
try { // do file IO here } catch (IOException e) { int HResult = System.Runtime.InteropServices.Marshal.GetHRForException(e) if (HResult == 32) // 32 = Sharing violation { // Recovery logic goes here } else { throw; // Or do whatever else here } }
While not yet released, C # 6.0 will, according to AC # 6.0 Language Preview , allow you to use this syntax to catch only an exchange violation:
try { // do file IO here } catch (IOException e) if (e.HResult == 32) // 32 = Sharing violation { // Recovery logic goes here }
Scott
source share