【问题标题】:How to prevent Directory.GetFiles to "check" recycle bin and other "unsafe" places?如何防止 Directory.GetFiles “检查”回收站和其他“不安全”的地方?
【发布时间】:2014-11-19 06:14:13
【问题描述】:

伙计们,我的应用程序中有一个函数可以使用GetFiles 方法在某个目录中搜索某个文件

System.IO.Directory.GetFiles(string path, string searchPattern, System.IO.SearchOption)

它工作正常,直到我选择要搜索的驱动器目录(D:\C:\ 等),因为它也在访问回收站,然后被限制

拒绝访问路径“D:\$RECYCLE.BIN\S-1-5-21-106145493-3722843178-2978326776-1010”。

还需要能够搜索子文件夹 (SearchOption.AllDirectories)。

如何跳过要搜索的地方?因为可能有任何其他文件夹也被拒绝访问。

我将 SKIP 大写,因为如果我使用 try catch 并捕获了异常,那么整个搜索也会失败。

谢谢。请澄清您需要的任何内容。

【问题讨论】:

标签: c# io directory getfiles


【解决方案1】:

已编辑以更清晰。

当递归扫描目录树时,比如使用以目录作为参数的递归方法,您可以获得目录的属性。然后检查它是否是系统目录,而不是像“C:\”这样的根目录——在这种情况下,你想跳过那个目录,因为它可能是,例如回收站。

这是一些执行此操作的代码,并且还捕获了一些在我摆弄目录扫描时发生的常见异常。

void    scan_dir(string path)
{
    // Exclude some directories according to their attributes
    string[] files = null;
    string skipReason = null;
    var dirInfo = new DirectoryInfo( path );
    var isroot = dirInfo.Root.FullName.Equals( dirInfo.FullName );
    if (    // as root dirs (e.g. "C:\") apparently have the system + hidden flags set, we must check whether it's a root dir, if it is, we do NOT skip it even though those attributes are present
            (dirInfo.Attributes.HasFlag( FileAttributes.System ) && !isroot)    // We must not access such folders/files, or this crashes with UnauthorizedAccessException on folders like $RECYCLE.BIN
        )
    {   skipReason = "system file/folder, no access";
    }

    if ( null == skipReason )
    {   try
        {   files = Directory.GetFiles( path );
        }
        catch (UnauthorizedAccessException ex)
        {   skipReason = ex.Message;
        }
        catch (PathTooLongException ex)
        {   skipReason = ex.Message;
        }
    }

    if (null != skipReason)
    {   // perhaps do some error logging, stating skipReason
        return; // we skip this directory
    }

    foreach (var f in files)
    {   var fileAttribs = new FileInfo( f ).Attributes;
        // do stuff with file if the attributes are to your liking
    }

    try
    {   var dirs = Directory.GetDirectories( path );
        foreach (var d in dirs)
        {   scan_dir( d ); // recursive call
        }
    }
    catch (PathTooLongException ex)
    {   Trace.WriteLine(ex.Message);
    }
}

【讨论】:

  • 可以否决投票者请发表评论?我的建议对我有用,我扫描了整个驱动器并以这种方式避免了除 root 之外的系统目录。这可以防止那些明显预期的情况引发异常,这对我来说似乎更可取。
  • (虽然在处理此类操作时您显然应该捕获异常,但如果您可以首先阻止它们发生,我不会依赖它们,因为某些东西很容易检查)
  • 我确实意识到 OPs 问题有些陈旧,并且发布了重复的链接。我不太喜欢其他地方的回复和另一个在这里但最近被删除的回复,建议完全依赖例外。由于我更喜欢​​防止明显预期的事情引发异常(这可能会减慢您对数千个文件夹的扫描速度),所以我想我会发布这个。我发现这个线程是因为几天前,我自己正在寻找解决这个问题的方法。找到一个比我在其他地方看到的更喜欢的一个,因此回来了。
猜你喜欢
  • 2010-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 2013-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
相关资源
最近更新 更多