BoJack Horseman
BoJack Horseman

Reputation: 173

Delete Folder If Only Contains Text File

I have been using this to delete empty folders, and it suits my needs perfectly. I need to add one stipulation to still delete the folder if it only contains a SINGLE .txt file. How should I alter this syntax to still delete the directory if it only contains a .txt file?

static void Main(string[] args)
{
    string path = @"C:\Test\";
}
public 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);
        }
    }           
}

EDIT

This produces syntax error, but I think it is what I was trying to accomplish

if (Directory.GetFiles(Path.GetExtension) == ".txt")

Upvotes: -4

Views: 244

Answers (1)

MutantNinjaCodeMonkey
MutantNinjaCodeMonkey

Reputation: 1249

Something like this?

public static void processDirectory(string startLocation)
{
    foreach (var directory in Directory.GetDirectories(startLocation))
    {
        processDirectory(directory);
        var aFiles = Directory.GetFiles(directory);
        var noFiles = aFiles.Length == 0 || (aFiles.Length == 1 && aFiles.Count(file => Path.GetExtension(file) == ".txt") == 1);
        if (noFiles && Directory.GetDirectories(directory).Length == 0)
        {
            Directory.Delete(directory, true);
        }
    }           
}

UPDATE: OP modified question to specify a SINGLE file. Answer modified to match.

Upvotes: -2

Related Questions