Click here to Skip to main content
15,905,148 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a fileinfo list of files that I want to keep and I want to delete the files that are not on that list from a folder. How can I do this? Like looping through each file in the directory and if it is not one of the files specified in the list then it should be deleted otherwise keep it. Thank you
Posted
Comments
Richard MacCutchan 24-Dec-13 12:17pm    
That sounds like the obvious way to do it.

1 solution

Pretty simple:
This just creates the list of files to keep:
C#
List<FileInfo> keepers = Directory.GetFiles(@"D:\Temp", "*.jpg").Select(f => new FileInfo(f)).ToList();
Then just:
C#
string[] files = Directory.GetFiles(@"D:\Temp");
var deleteList = files.Except(keepers.Select(fi => fi.FullName));
foreach (string s in deleteList)
    {
    File.Delete(s);
    }
 
Share this answer
 
Comments
Karthik_Mahalingam 24-Dec-13 23:36pm    
5

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



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