Click here to Skip to main content
14,934,560 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How do I find characters in filenames and if found, delete all files that are not in search? For example: I have 5 file in directory with name:


What I have tried:

I need search name of file: "123" It results return found will delete 4 file 2,3,4,5 and repeat this when more files are added Can anyone help me do this?
Updated 29-Jan-21 16:14pm

You could use something like this to get the non-matching files:
var files = from f in Directory.EnumerateFiles("C:\\Temp")
            where f.Contains("123") == false
            select f;
Sơ Mi Tv 29-Jan-21 21:26pm
Can you help me code delete file if the content in the search is not mactching as the file name to search?
RickZeeland 1-Feb-21 2:23am
Use foreach(file in files)
Look at using the Directory.GetFiles method override that includes a search string: Directory.GetFiles Method (System.IO) | Microsoft Docs[^] - it returns an array of matching files.
The search string can't include negatives though, so there are two solutions:
1) Call GetFiles twice: once to get all "*.txt" files, and once to get just "*123*.txt" files. You can then use the Linq Except method to exclude them, giving you a list of files to delete.
string[] all = Directory.GetFiles(path, "*.txt");
string[] match = Directory.GetFiles(path, "*123*.txt");
var toDelete = all.Except(match);
You may have to change the sel3ect criteria if the folder path can contain the search string with teh second option.
2) Call Getfiles once to get all "*.txt" files, and then use the Linq Where method to remove the ones you want to keep:
string[] all = Directory.GetFiles(path, "*.txt");
var toDelete = all.Where(f => !f.ToLower().Contains("man"));
Sơ Mi Tv 28-Jan-21 7:29am
Can you show more detailed code? Example of placing code in if_else statement pair. Because I'm beginner :)
OriginalGriff 28-Jan-21 7:57am
How much more detailed do you need it: two full solutions that give you a list of "files to delete" ...
With your solution I don't really understand it yet. Can you help me with code in my project when I call DelFile ()?
private void CompeteLog ()
            string[] all = Directory.GetFiles(cbChoisePS.Text, "*.tar");
            string[] match = Directory.GetFiles(cbChoisePS.Text, "_ACB-");
            var toDelete = all.Except(match);
              \\ i don't understand we are delete file where?
Richard Deeming 1-Feb-21 10:00am
If you want to reply to a solution, click the "Have a Question or Comment?" button under that solution and post a comment.

Do not post your question as a new "solution".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900