Is it possible to check in C # whether someone is in the directory?

I need to do this before removing it. In my opinion, this is the fastest way to check, rather than trying to check for the employment of each file in the directory.

In WinServer, for example, in the management tab you can find out.

Is there any wrapper for this case in C #?

  • The delete option in try { } catch{ } (deleted - well, nicely, no - put an error in the log) does not fit? - i-one
  • @ i-one, I wanted to prevent all possible errors, for example, the directory is used (The most frequent error.) With try / catch, something will be removed, but something will not. - iluxa1810
  • The main problem of any preliminary checks - someone can open the file immediately after checking. - Pavel Mayorov

1 answer 1

Option 1.

Try to rename the directory. If it has locked files, it will not be possible to rename it.

This method does not work on Windows XP.

Option 2.

Before deleting files, open them all in read-write mode, indicating the permission of parallel deletion ( FileMode.Open , FileAccess.ReadWrite , FileShare.Delete ).

If they have successfully opened - delete them, and after removal - close.

If at least one file could not be opened, it means that it is open by someone else. Close the files back and do not touch them.

This method works on Windows XP, thanks to Yurii Manziuk for checking.

  • Option 2 - works - Yurii Manziuk
  • Yes, it was Khryusha who checked it while there was a possibility - Yurii Manziuk
  • And why the first method does not work in XP? - iluxa1810
  • @ iluxa1810 because XP allows renaming of folders while the file is open and locked inside. - Pavel Mayorov
  • And get a list of users in the director can not be? - iluxa1810