I'm using this solution to delete all empty folders and subdirectories in a certain path:
static void Main(string[] args)
{
processDirectory(@"c:\temp");
}
private static void processDirectory(string startLocation)
{
foreach (var directory in Directory.GetDirectories(startLocation))
{
processDirectory(directory);
if (Directory.GetFiles(directory).Length == 0 &&
Directory.GetDirectories(directory).Length == 0)
{
Directory.Delete(directory, false);
}
}
}
It works perfectly. But I want to delete all empty folders and also folders which are not empty but also doesn't contain files with the .dvr
extension.
For example, my folder has the files:
a.log
b.log
c.dvr
d.dat
So this folder can't be deleted, for it contains a file with the dvr extension.
How can I filter it? (I'm using GTK# but I believe C# code will work, since this solution is a C# code)
Use Del *. in batch file to remove files with no extension. use Dir /A-D *. to list down all files with no extension.
Using rm Command To remove a file with a particular extension, use the command 'rm'. This command is very easy to use, and its syntax is something like this. In the appropriate command, 'filename1', 'filename2', etc., refer to the names, plus their full paths.
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r .
Unfortunately error handling is very exception based in IO operations. And Directory.Delete throws an IOException if the directory is not empty. So you'll have to delete the files manually:
private static bool processDirectory(string startLocation)
{
bool result = true;
foreach (var directory in Directory.GetDirectories(startLocation))
{
bool directoryResult = processDirectory(directory);
result &= directoryResult;
if (Directory.GetFiles(directory, "*.dvr").Any())
{
result = false;
continue;
}
foreach(var file in Directory.GetFiles(directory))
{
try
{
File.Delete(file);
}
catch(IOException)
{
// error handling
result = directoryResult = false;
}
}
if (!directoryResult) continue;
try
{
Directory.Delete(directory, false);
}
catch(IOException)
{
// error handling
result = false;
}
}
return result;
}
I would use Directory.EnumerateFiles to see if a directory contains the file you're looking for. Changing your code to be:
static void Main(string[] args)
{
processDirectory(@"c:\temp");
}
private static void processDirectory(string startLocation)
{
foreach (var directory in Directory.GetDirectories(startLocation))
{
processDirectory(directory);
if (Directory.GetDirectories(directory).Length == 0 ||
Directory.EnumerateFiles(directory, "*.dvr").Length == 0
)
{
Directory.Delete(directory, false);
}
}
}
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