I'm writing a windows service that might delete a file at some point. Because the service is dealing with regular file IO it's possible that a file can be in use during deletion.
Currently I'm trying to delete and react later when an exception happens. Code looks something like this:
try
{
File.Delete(file);
Status = ResponseStatus.Ok;
}
catch (IOException e)
{
Status = ResponseStatus.FileInUse;
}
finally
{
return Status;
}
How can I determine if a file in use without using an exception?
There's no point in trying to detect up front whether the file is in use - what if someone opens the file between your detection code and your deletion code? You're still going to need your existing code to cope with that case.
The code you already have is exactly the right way to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With