Is there a programmatic way to determine if a file is in use?
3 answers
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 to share
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 to share