CopalFreak
CopalFreak

Reputation: 63

C# delete files in folder with filter

I am using SharpDevelop to write a C# program (not console). I want to delete files within a specified directory, but be able to EXCLUDE files beginning, ending, or containing certain words.

TO completely delete ALL files in a folder I am using this :

private void clearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

    foreach(FileInfo fi in dir.GetFiles())
    {
        fi.Delete();
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        clearFolder(di.FullName);
        di.Delete();
    }
}

I use it like

ClearFolder("NameOfFolderIWantToEmpty");

Is there a way to modify this so that I can delete all files and direcotries EXCEPT those files and directories containing specific words?

Something like :

CleanFolder(FolderToEmpty,ExcludeAllFileAndDirectoriesContaingThisPhrase);

so that if I did

CleanFolder("MyTestFolder","_blink");

It would NOT delete files and directories with names like

_blinkOne (file)

Test_blineGreen (file)

Test_blink5 (directory)

_blinkTwo (file within the Text_blink5 directory)

Folder_blink (empty directory)

but WOULD delete files and directories like

test (file)

test2 (directory)

test3_file (file within test2 directory)

test4 (empty directory)

I suspect I might have to iterate through each file and directory, checking them one at a time for the matching filter and deleting it if it does not match, but I am not sure how to do that.

Something with FileInfo() and DirectoryInfo() perhaps?

Can somebody help by providing a working example? (modified version of the above is preferred, but if a new method is required, as long as it doesn't require an outside dll, is OK.

Upvotes: 3

Views: 16605

Answers (4)

Jason Watkins
Jason Watkins

Reputation: 3785

Use the Directory.GetFiles(string, string) method to get a list of files that match your pattern, and use Enumerable.Except(IEnumerable<T>) to get the files you actually want to delete.

string pattern = "*.*";
var matches = Directory.GetFiles(folderName, pattern);
foreach(string file in Directory.GetFiles(folderName).Except(matches))
    File.Delete(file);

There's no need to use DirectoryInfo here, since you appear to be concerned only with manipulating the files in the directory.

Upvotes: 4

CopalFreak
CopalFreak

Reputation: 63

I think I have a solution that will work for me. Posting the full code here so that others may use it, tweak it, and/or examine it for possible flaws. This is my first time using StackOverFlow, and knowing that I have this resource available to search and the ability to ask questions and people can actually help, is a great comfort to me as a person who is new to all of this stuff.

Thanks a ton everybody!

// Search directory recursively and delete ALL sub-directories and files

// with names that do NOT contain the given search pattern

private void clearFolderWithFilter(string folderName, string filesToExclude)
{
    DirectoryInfo dir = new DirectoryInfo(folderName);

    foreach(FileInfo fi in dir.GetFiles())
    {
        if(!fi.Name.Contains(filesToExclude))
        {
            // System.Diagnostics.Debug.WriteLine("DELETING file " + fi + " because it does NOT contain '" + filesToExclude + "' ");
            fi.Delete();
        } else {
            // System.Diagnostics.Debug.WriteLine("SAVING file " + fi + " because it contains '" + filesToExclude + "' ");
        }
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        if(!di.Name.Contains(filesToExclude))
        {
            // System.Diagnostics.Debug.WriteLine("DELETING directory " + di + " because it does NOT contain '" + filesToExclude + "' ");
            clearFolderWithFilter(di.FullName, filesToExclude);
            di.Delete();
        } else {
            // System.Diagnostics.Debug.WriteLine("SAVING directory " + di + " because it contains '" + filesToExclude + "' ");
        }
    }
}

Usage :

clearFolderWithFilter(@"C:\Path\MyFolder","DoNotDelete_");

Upvotes: 0

Inisheer
Inisheer

Reputation: 20794

Just test to see if the FileInfo.Name property (string) StartsWith or EndsWith a specified string.

    foreach (FileInfo fInfo in di.GetFiles())
    {
        if (!fInfo.Name.StartsWith("AAA") || 
            !fInfo.Name.EndsWith("BBB"))
        {
            fInfo.Delete();
        }
    }

Or if you are looking for a word anywhere in the filename, use the Contains method:

    foreach (FileInfo fInfo in di.GetFiles())
    {
        if (!fInfo.Name.Contains("CCC")) 
        {
            fInfo.Delete();
        }
    }

Upvotes: 3

Shaharyar
Shaharyar

Reputation: 12459

if(!fi.Name.Contains("_blink"))
      fi.Delete();

Upvotes: 0

Related Questions