-->

Is there a way to instantly check whether a direct

2020-08-17 07:33发布

问题:

I want to move a directory and all of its subdirectories with Directory.Move.

Before I do that, however, I want to check whether any of the files and subfiles in the directory and its subdirectories are being used by other processes.

Then, before the move, I'd like to lock the directory to other processes, so I can be sure that Directory.Move won't throw any exceptions.

What is the best way to accomplish that?

I would like to avoid checking for the usage of the individual files file by file, because the fact that the file isn't used when the software checks for it does not mean that it won't be used when the movement process starts.

回答1:

There is no way to lock the folder (+ sub folders) so you'll always end up with a race condition and there is no guarantee that there will be no exception.

There is always the possibility that something changes in between the check and the move so things can go wrong.

Just try to move the folder and retry later if not succeeding.

See also: Delphi: Check whether file is in use (this is a similar question, just ignore the Delphi part)



回答2:

Description

You can put your File opteration into a try .. catch block and catch IOException.

Sample

try 
{
   // try to move
} 
catch (System.IO.IOException ex) 
{
   // file used by another process or other IO Exception
}

More Information

  • MSDN - IOException Class