如何删除文件夹中的所有文件,但保留已添加到FileInfo列表中的文件 [英] How to delete all files in a folder but keep the ones that have been added to a FileInfo list

查看:120
本文介绍了如何删除文件夹中的所有文件,但保留已添加到FileInfo列表中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想要保留的文件的fileinfo列表,我想从文件夹中删除不在该列表中的文件。我怎样才能做到这一点?就像循环遍历目录中的每个文件一样,如果它不是列表中指定的文件之一,则应删除它,否则保留它。谢谢

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

推荐答案

非常简单:

这只是创建要保留的文件列表:

Pretty simple:
This just creates the list of files to keep:
List<FileInfo> keepers = Directory.GetFiles(@"D:\Temp", "*.jpg").Select(f => new FileInfo(f)).ToList();

然后只需:

Then just:

string[] files = Directory.GetFiles(@"D:\Temp");
var deleteList = files.Except(keepers.Select(fi => fi.FullName));
foreach (string s in deleteList)
    {
    File.Delete(s);
    }


这篇关于如何删除文件夹中的所有文件,但保留已添加到FileInfo列表中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆