Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine that a file is in use before deletion?

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?

like image 915
Vadim Avatar asked Nov 30 '22 06:11

Vadim


1 Answers

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.

like image 190
RichieHindle Avatar answered Dec 04 '22 12:12

RichieHindle