简体   繁体   中英

Delete all files and directories except the ones in a list

I have two tasks in hand

  1. Get 10 latest files from a folder lets say C:\\Temp and
  2. Delete any other folders and files.

I got the first item working by using the below code, thanks for our friends in Stack Overflow.

var imgFiles = (from f in directory.GetFiles(fileType,SearchOption.AllDirectories)
                            orderby f.LastWriteTime descending
                            select f).Take(numberOfFilesToFetch).ToArray();

I need some help with point 2. Some sample C# code will be really helpful.

If you only need to delete the files I propose that you only get the list of the files to deleted, So you can use Skip instead of Take

Others aproach are calling GetFiles again with an Except call which is not very efficient if you dont need the list of files to ignore during the delete process

var filesToBeDeleted = (from f in Directory.GetFiles(fileType,SearchOption.AllDirectories)
                            orderby f.LastWriteTime descending
                            select f).Skip(numberOfFilesToFetch).ToArray();

foreach (var file in filesToBeDeleted)
{
    file.Delete();
}

string [] subdirectoryEntries = Directory.GetDirectories("c:\\temp");

foreach(string dir in subdirectoryEntries)
{
    Directory.Delete(dir) ;
}

I recommend that you add a try,catch for the delete operations

foreach (var file in directory.GetFiles().Except(imgFiles))
{
    file.Delete();
}
var filesToBeDeleted = directory.GetFiles(fileType, SearchOption.AllDirectories)
                                .Except(imgFiles).ToArray();
for (int i = filesToBeDeleted.Length; i >= 0; i--)
    filesToBeDeleted[i].Delete();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM