2

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
CopalFreak
  • 53
  • 1
  • 2
  • 11
  • All the answers are correct, if any one of them helped you so choose it as answer so no one will waste time to read your question again , because it has already been answered. – Shaharyar Mar 21 '13 at 19:21
  • possible duplicate of [C# - Delete files from directory if filename contains a certain word](http://stackoverflow.com/questions/1620366/c-sharp-delete-files-from-directory-if-filename-contains-a-certain-word) – Shadow The GPT Wizard Jan 01 '14 at 08:41

4 Answers4

3

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();
        }
    }
Inisheer
  • 20,376
  • 9
  • 50
  • 82
  • This method seems to check the files in the main directory only, and none of the subdirectories(their names) or files within those subdirectories. I think it might be a good method for me to use, but I am just missing some part of it that would make it do that. Thanks! – CopalFreak Mar 23 '13 at 00:51
  • I was able to modify a combination of this and another answer to get it working. (wish I could 'VoteUp' but still new here).Thanks! – CopalFreak Mar 23 '13 at 01:28
3

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.

Jason Watkins
  • 3,766
  • 1
  • 25
  • 39
  • I am wanting to delete all directories and files and sub-directories (and all the files-n- directories within)..etc. that do NOT match the search pattern. Will give this a shot and see what happens. will post results when resolved. THANKS! – CopalFreak Mar 22 '13 at 21:17
  • @CopalFreak: I understand that. the best way to do that is to get a list of files that *do* match, and delete all files that aren't in the match list. – Jason Watkins Mar 22 '13 at 22:09
  • Where you have "Except(matches))"..I get one of those lovely "System.Array does not contain a definition for 'Except'.." errors.. Am I missing a "using System.Something;" at the top? I have System and System.IO .. not sure where the Except (or Contains ) might be.. Google searches dont seem to be helping much, I suspect because 'Except' may not be part of the standard c# stuff...not sure on that tho..am still a noob. hehe . Any suggestions? Thanks!! – CopalFreak Mar 22 '13 at 23:32
  • Not sure if this matters, but I do not want to use .NET stuff, because, as I currently understand it, it would result in having to include an extra .dll file and/or making the program larger. For my needs, I want to keep it a single portable exe file. – CopalFreak Mar 22 '13 at 23:46
  • @CopalFreak: Except is a LINQ method. You need `using System.Linq` and a reference to `System.Core.dll`. Otherwise, you could replace the except method with `if(matches.Contains(file)) continue;` in the loop body. – Jason Watkins Mar 22 '13 at 23:53
  • I was able to modify a combination of this and another answer to get it working. (wish I could 'VoteUp' but still new here).Thanks! – CopalFreak Mar 23 '13 at 01:29
  • please add the quotation marks arround your pattern string: - string pattern = "*.*"; – Ensai Tankado Aug 29 '21 at 08:46
0
if(!fi.Name.Contains("_blink"))
      fi.Delete();
Shaharyar
  • 12,254
  • 4
  • 46
  • 66
  • I think I tried using this method before and it had some problem with the 'Contains' part. Will try anyway and will post results when I have em. THANKS! – CopalFreak Mar 22 '13 at 21:19
  • Getting an error that says there is no definition for 'Contains' and no extension method 'Contains'. As with the other answer here, I suspect I am missing a "using System.Something" up at the top, but no clue what that would be. Would like to try out both of these methods though. Thanks! – CopalFreak Mar 22 '13 at 23:38
  • after adding "using System.Linq" per Jason Watkins suggestion, I found that, the way I currently tested this method, would only check the main directory itself and none of the files or subfolders within. Thanks though. – CopalFreak Mar 23 '13 at 00:47
  • I was able to modify a combination of this and another answer to get it working. (wish I could 'VoteUp' but still new here).Thanks! – CopalFreak Mar 23 '13 at 01:28
0

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_");
CopalFreak
  • 53
  • 1
  • 2
  • 11
  • This code will throw an exception as it will try to delete folder that contain folders named "DoNotDelete_". Those were not deleted so their ancestor folders won't be empty and di.Delete() will fail. I would suggest tweaking this by returning an indication for whether a file or folder was skipped so that there will not be an attempt to delete a folder if something was skipped inside it. This should be OR-ed with the results of previous return values so that we won't try to delete c:\Path\MyFolder if it contains the path c:\Path\MyFolder\A\B\C\D\DoNotDelete_. – shwartz Oct 06 '14 at 10:27