Is there a programmatic way to determine if a file is in use?

Case and point: I need to open an Excel file via Interop, and that would help a lot to avoid ugly COM errors if I knew the file was in use.

Besides trying to open the file and catch the exception, is there a programmatic way to determine if the file is in use?

+2


a source to share


3 answers


To access exclusive access, you need to use a Win32 API file (CreateFile or lopen) and check the return value.



+2


a source


Whichever method you use, nothing guarantees that between your invocation and the actual opening of the file, that other process has not opened the file.

Some pseudo codes:



internal File OpenExcelFile(String fileName)
{
    File file = null;
    var fileOpened = SomeLibrary.IsFileOpened(fileName);

    if (!fileOpened)
    {
       // Nothing garanties that another process didnt grabbed the file between call and that the file is still closed!!!
       file = ExcelLibrary.OpenFile(fileName);
    }

    return file;
}

      

0


a source


The worse the worse. Not only do you need to catch the exception, you need to use reflection to eliminate it from other errors. At least this is the only solution I have found.

        try
        {
            using (StreamWriter sw = new StreamWriter(filepath, false))
            {
                sw.Write(contents);
            }
        }
        catch (System.IO.IOException exception)
        {
            if (!FileUtil.IsExceptionSharingViolation(exception))
                throw;
        }

      

...

    public static bool IsExceptionSharingViolation(IOException exception)
    {
        Type type = typeof(Exception);

        PropertyInfo pinfo = type.GetProperty("HResult", BindingFlags.NonPublic | BindingFlags.Instance);

        uint hresult = (uint)(int)pinfo.GetValue(exception, null);

        //ERROR_SHARING_VIOLATION = 32
        //being an HRESULT adds the 0x8007

        return hresult == 0x80070020;
    }

      

0


a source







All Articles