I am doing an archive service for logs. Since some files are open and in use I can’t archive them until they are not in use anymore. The only way I can figure out how to see if the file is open by another process is the code below.
I hate the code there must be a better way. Is there a better way?
try
{
using (FileStream stream = File.Open("SomeFile.txt", FileMode.Open, FileAccess.ReadWrite))
{
// Do nothing just seeing if I could open it.
return true;
}
}
catch (IOException)
{
// Exception so File is in use and can't open
return false;
}
EDIT: Please note, that I do not want to catch the exception. I would rather avoid the exception entirely. I would rather have some magic function for example IsFileInUser(string fileName) that would return a boolean WITHOUT catching exceptions underneath.
A way I have see is using OpenFile of PInvoke.
Here is what I came up with.
First here is the bad way of doing it by exception.
On my machine this method took about 10 million ticks when the file was in use.
The other way is using the kernel32.dll
Here is the function
This ran in about 1.8 million ticks. Over an 8 million ticks difference from the exception method.
However when file it not in use meaning no exception is thrown the speed of the “BAD” method is 1.3 million and the kernel32.dll is 2 million. About an 800k ticks better. So using the Exception method would be better if I knew the file would be not be in use about 1/10th of the time. However the one time it is, it is an extremely expensive ticks operation compared to the kernel32.dll.