【问题标题】:Access to the path 'd:\$RECYCLE.BIN\S-1-5-21-494745725-312220573-749543506-41600' is denied拒绝访问路径“d:\$RECYCLE.BIN\S-1-5-21-494745725-312220573-749543506-41600”
【发布时间】:2016-01-04 02:05:09
【问题描述】:

我是 C# 新手。我有一个文本框,我在其中输入要搜索的文件和一个“搜索”按钮。在搜索时钟上,我希望它填充文件夹中的文件,但出现上述错误。以下是我的代码:

string[] directories = Directory.GetDirectories(@"d:\",
                                              "*",
                                              SearchOption.AllDirectories);
string file = textBox1.Text;
DataGrid dg = new DataGrid();

{
    var files = new List<string>();
     foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady))
        {
        try
        {
            files.AddRange(Directory.GetFiles(d.RootDirectory.FullName,  file , SearchOption.AllDirectories));
        }
        catch(Exception ex)
        {
            MessageBox.Show("the  exception is " + ex.ToString());
            //Logger.Log(e.Message); // Log it and move on
        }
}

请帮我解决它。谢谢

【问题讨论】:

  • 很明显你不应该进入那个垃圾箱。
  • 只是对 d: 上的所有目录进行全面搜索会导致 大量 系统文件夹普通用户帐户不应访问,并且您将被拒绝访问。
  • 我的 D 盘没有回收站。我只是在搜索文件夹或文件。我知道我们不应该扔垃圾。请让我知道我是如何避免在垃圾箱中搜索的。
  • 在 d: 盘上确实有一个回收站,即使它隐藏在文件资源管理器中。除此之外,使用AllDirectories 时不能只跳过文件夹,最好是catch UnauthorizedAccessException 并跳过该目录。

标签: c#


【解决方案1】:

在搜索可能包含无法访问子文件夹的文件夹时,最重要的规则是:

请不使用SearchOption.AllDirectories!

请改用SearchOption.TopDirectoryOnly,并结合递归搜索对所有可访问的目录进行搜索。

使用SearchOption.AllDirectories,一个访问冲突会在处理任何文件/目录之前中断整个循环。但是如果你使用SearchOption.TopDirectoryOnly,你只会跳过无法访问的内容。

对于每个子目录使用Directory.GetAccessControl() 有更困难的方法,先检查您是否有权访问某个目录(尽管此选项相当困难 - 我不建议您这样做,除非您确切知道访问系统工作)。

对于递归搜索,我实现了这段代码供我自己使用:

public static List<string> GetAllAccessibleDirectories(string path, string searchPattern) {
    List<string> dirPathList = new List<string>();
    try {
        List<string> childDirPathList = Directory.GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly).ToList(); //use TopDirectoryOnly
        if (childDirPathList == null || childDirPathList.Count <= 0) //this directory has no child
            return null;
        foreach (string childDirPath in childDirPathList) { //foreach child directory, do recursive search
            dirPathList.Add(childDirPath); //add the path
            List<string> grandChildDirPath = GetAllAccessibleDirectories(childDirPath, searchPattern);
            if (grandChildDirPath != null && grandChildDirPath.Count > 0) //this child directory has children and nothing has gone wrong
                dirPathList.AddRange(grandChildDirPath.ToArray()); //add the grandchildren to the list
        }
        return dirPathList; //return the whole list found at this level
    } catch {
        return null; //something has gone wrong, return null
    }
}

这就是你的称呼

List<string> accessibleDirs = GetAllAccessibleDirectories(myrootpath, "*");

然后,您只需在所有可访问目录中搜索/添加文件。

注意:这个问题很经典。我相信还有其他更好的解决方案。

如果在获得所有可访问目录后,您特别希望避免某些目录,您还可以使用目录名称的一部分作为关键字(即Recycle.Bins)通过 LINQ 过滤 List 结果。

【讨论】:

    【解决方案2】:

    正如 Ian 在他的 post 中指定的那样,不要使用递归文件列表 (Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories)),因为第一个异常将停止进一步处理。

    此外,为了在一定程度上缓解此类问题并总体上获得更好的结果,您应该以Administrator 运行此程序。这可以通过在 Windows 资源管理器中右键单击您的应用程序,然后检查 Compatibility 选项卡上的 Run this program as an administrator 选项来完成。

    此外,您应该使用如下代码进行搜索,因此中间异常不会停止进一步搜索。

    static void Main(string[] args) {
        string fileToFind = "*.jpg";
        var files = new List<string>();
    
        foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady))
            files.AddRange(FindDirectory(fileToFind, d.RootDirectory.FullName));
    }
    
    /// <summary>
    /// This function returns the full file path of the matches it finds. 
    ///   1. It does not do any parameter validation 
    ///   2. It searches recursively
    ///   3. It eats up any error that occurs when requesting files and directories within the specified path
    ///   4. Supports specifying wildcards in the fileToFind parameter.
    /// </summary>
    /// <param name="fileToFind">Name of the file to search, without the path</param>
    /// <param name="path">The path under which the file needs to be searched</param>
    /// <returns>Enumeration of all valid full file paths matching the file</returns>
    public static IEnumerable<string> FindDirectory(string fileToFind, string path) {
    
        // Check if "path" directly contains "fileToFind"
        string[] files = null;
        try {
            files = Directory.GetFiles(path, fileToFind);
        } catch { }
    
        if (files != null) {
            foreach (var file in files)
                yield return file;
        }
    
    
        // Check all sub-directories of "path" to see if they contain "fileToFInd"
        string[] subDirs = null;
        try {
            subDirs = Directory.GetDirectories(path);
        } catch { }
    
        if (subDirs == null)
            yield break;
    
        foreach (var subDir in subDirs)
            foreach (var foundFile in FindDirectory(fileToFind, subDir))
                yield return foundFile;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 2017-11-20
      • 1970-01-01
      • 2016-11-11
      • 2011-03-29
      相关资源
      最近更新 更多