Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulate waiting on File.Open in C# when file is locked

I have, essentially, the same problem as this poster, but in C#: Waiting until a file is available for reading with Win32

More information: we have code that calls File.Open in one of our projects, that occasionally dies when the file is already opened by another process (EDIT: or thread):

FileStream stream = File.Open(m_fileName, m_mode, m_access);
/* do stream-type-stuff */
stream.Close();

File.Open will throw an IOException (which is currently quietly swallowed somewhere), whose HResult property is 0x80070020 (ERROR_SHARING_VIOLATION). What I would like to do is this:

FileStream stream = null;
while (stream == null) {
    try {
        stream = File.Open(m_fileName, m_mode, m_access, FileShare.Read);
    } catch (IOException e) {
        const int ERROR_SHARING_VIOLATION = int(0x80070020);
        if (e.HResult != ERROR_SHARING_VIOLATION)
            throw;
        else
            Thread.Sleep(1000);
    }
}
/* do stream-type-stuff */
stream.Close();

However, HResult is a protected member of Exception, and cannot be accessed -- the code does not compile. Is there another way of accessing the HResult, or perhaps, another part of .NET I might use to do what I want?

Oh, one final caveat, and it's a doozy: I'm limited to using Visual Studio 2005 and .NET 2.0.

like image 221
Blair Holloway Avatar asked Jun 29 '10 06:06

Blair Holloway


1 Answers

You can call Marshal.GetHRForException() within the catch clause to get the error code. No need for reflection:

using System.Runtime.InteropServices;

if (Marshal.GetHRForException(e) == ERROR_SHARING_VIOLATION)
    ....
like image 103
Igal Tabachnik Avatar answered Sep 21 '22 10:09

Igal Tabachnik