加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何只获取可以复制的文件?

发布时间:2020-12-16 00:23:09 所属栏目:百科 来源:网络整理
导读:我有这行代码:(使用LINQ) //string folder -- folder browser dialog.listFiles = Directory.GetFiles(folder,"*.xml",SearchOption.AllDirectories).Select( fileName = Path.GetFullPath(fileName)).ToList(); 但有时我的程序会找到受保护的文件,例如系统
我有这行代码:(使用LINQ)

//string folder <-- folder browser dialog.
listFiles = Directory.GetFiles(folder,"*.xml",SearchOption.AllDirectories).Select(
                    fileName => Path.GetFullPath(fileName)).ToList();

但有时我的程序会找到受保护的文件,例如系统文件甚至无法打开的系统文件夹.

我怎样才能超越这个问题:

只获取打开/免费文件夹的文件名.

解决方法

这可能是个问题.如果它在遍历目录时抛出异常,则会停止.

如果要忽略这些目录并继续运行,则必须编写一个递归方法来执行此操作:

List<string> GetFiles(string folder,string filter)
{
    List<string> files = new List<string>();
    try
    {
        // get all of the files in this directory
        files.AddRange(Directory.GetFiles(folder,filter));
        // Now recursively visit the directories
        foreach (var dir in Directory.GetDirectories(folder))
        {
            files.AddRange(GetFiles(dir,filter));
        }
    }
    catch (UnauthorizedAccessException)
    {
        // problem accessing this directory.
        // ignore it and move on.
    }
    return files;
}

一个更高效的内存版本是:

private List<string> GetFiles(string folder,string filter)
    {
        var files = new List<string>();

        // To create a recursive Action,you have to initialize it to null,// and then reassign it. Otherwise the compiler complains that you're
        // using an unassigned variable.
        Action<string> getFilesInDir = null;
        getFilesInDir = new Action<string>(dir =>
            {
                try
                {

                    // get all the files in this directory
                    files.AddRange(Directory.GetFiles(dir,filter));
                    // and recursively visit the directories
                    foreach (var subdir in Directory.GetDirectories(dir))
                    {
                        getFilesInDir(subdir);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    // ignore exception
                }
            });

        getFilesInDir(folder);
        return files;
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读