Check if file is locked or catch error for trying to open

Posted by Duncan Matheson on Stack Overflow See other posts from Stack Overflow or by Duncan Matheson
Published on 2012-06-25T03:12:21Z Indexed on 2012/06/25 3:15 UTC
Read the original article Hit count: 257

I'm trying to handle the problem where a user can try to open, with an OpenFileDialog, a file that is open by Excel.

Using the simple FileInfo.OpenRead(), it chucks an IOException, "The process cannot access the file 'cakes.xls' because it is being used by another process." This would be fine to display to the user except that the user will actually get "Debugging resource strings are unavailable" nonsense.

It seems not possible to open a file that is open by another process, since using FileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite) chucks a SecurityException, "File operation not permitted. Access to path 'C:\whatever\cakes.xls' is denied.", for any file. Rather unhelpful.

So it's down to either finding some way of checking if the file is locked, or trying to catch the IOException. I don't want to catch all IOExceptions and assume they're all locked file errors, so I need some sort of way of classifying this type of exception as this error... but the "Debugging resource strings" nonsense along with the fact that that message itself is probably localized makes it tricky. I'm partial trust, so I can't use Marshal.GetHRForException.

So: Is there any sensible way of either check if a file is locked, or at least determining if this problem occurred without just catching all IOExceptions?

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about filestream