I have a folder which consists of several files and sub folders. I want to empty it but some files may be in use. So I want to do a check if the file is in use and then based on that I want to delete it or skip it. Best possible way ?
Thanks.
I have a folder which consists of several files and sub folders. I want to empty it but some files may be in use. So I want to do a check if the file is in use and then based on that I want to delete it or skip it. Best possible way ?
Thanks.
The most quick and straight forward way to "delete-or-skip" files I can think of is ... swallowing the IOException
you get when something goes south while handling files.
//collectionOfFilesToDelete = string []{"path\file1.txt", "path\file2.txt", ...}
foreach(var fileName in collectionOfFilesToDelete)
try
{
File.Delete(fileName);
}
catch(IOException ex)
{
// empty on purpose!
}
I'm omitting all the accessory code (path handling etc.)
You roughly need to check as:
protected virtual bool IsFileinUse(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
return false;
}
Not possible as far as I know. You will get an Exception if you delete the folder. That's all you have as far as I know.
As Zeeshan put very well you can check every file in the folder, but that does not prevent someone to have a lock on the folder.
Also, how do you know the condition hasn't changed between checking and actual deleting
It's really just a case of catching the appropriate exception on File.Delete
and ignoring it, according to the docs an IOException
is thrown if a file is currently in use or locked
public static void ClearFolder(string targetDirectory, bool removeAfterwards)
{
// delete files in folder
foreach (var file in Directory.GetFiles(targetDirectory))
{
try
{
File.Delete(file);
}
catch (IOException)
{
// file is in use, skip
}
}
// process sub folders
foreach (var dir in Directory.GetDirectories(targetDirectory))
ClearFolder(dir, true);
// delete folder itself
if (removeAfterwards) {
Directory.Delete(targetDirectory);
}
}
...
ClearFolder(folderToClear, false);
See the link
Here you will find lot of accepted results. Basically you need to check the file to delete and if it is failed you may sure it is in use. Otherwise you can be sure it is not in use. Simple logic.
Just use a try catch block and try to delete the file.