Hello community,
it is really weird and wicked! To check if a file is in use I try the following code
// Proceed only when the application is closed by the user again bool closed = false; FileStream testStream; FileInfo fileInfoObjectForTest; while (!closed) { try { fileInfoObjectForTest = new FileInfo(filename); testStream = fileInfoObjectForTest.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); closed = true; testStream.Close(); } catch (Exception e) { } } updatefile();
i.e., before I invoke the updatefile method I check permanently if the file is in use because I know it is in use and the program has to wait until it is closed. This code works so far but there is a weirdness about it when a program (at least Excel) does a "Save", i.e., when you click the save button in the Excel Client. It is, the program jumps to the updatefile method though the Excel file was not closed but only saved!! Try it for yourself and tell me if you have the same behavior. This means for me that the testStream object can be created for the short period of time when the user clicks on save in the Excel Client (??) .. very peculiar! I searched in the Internet and saw a thread in this Forum with the title "FAQ: How do I check whether a file is in use?" where the first method in the thread is the same I use.
I also tried the method IsFileLocked in the mentioned forum thread that uses some win32 functionality with the same result as before, that is, when I click on the save button then the program leaves the while loop and jumps to the updatefile method. So the approach with trying to open a used file to get an exception to realise it is used seems not to be applicable for me.
Do you have any idea why this peculiar behavior happens and could you tell me how to solve this?
Thanks in advance!