在递归文件搜索中忽略没有权限的目录(System.UnauthorizedAccessException)

时间:2015-04-19 10:52:27

标签: c# directory

我的程序应该在所有驱动器和文件夹中搜索具有特定文件名的文件。在我的搜索开始时,它会在我的代码中的这一行抛出一个System.UnauthorizedAccessException

DirectoryInfo[] dirs = dir.GetDirectories();

这是我正在使用的代码。我怎么能修复它以便忽略具有此问题的目录并继续搜索。

static void Main(string[] args)
{
    DriveInfo[] allDrives = DriveInfo.GetDrives();

    foreach (DriveInfo d in allDrives)
    {
        searchDirectory(d.ToString(), true);
    }
}

public static void searchDirectory(string drive, bool doSubDirs)
{
    DirectoryInfo dir = new DirectoryInfo(drive);
    DirectoryInfo[] dirs = dir.GetDirectories();

    FileInfo[] files = dir.GetFiles();
    foreach (FileInfo file in files)
    {
        if (file.Name.Contains("something"))
        {
             do something.... xD
        }
    }

    if (copySubDirs)
    {
        foreach (DirectoryInfo subdir in dirs)
        {
            //string temppath = Path.Combine(destDirName, subdir.Name);
            searchDirectory(subdir.FullName, doSubdirs);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如何简单地将代码包装在try catch中?

        DirectoryInfo dir = new DirectoryInfo(drive);
        try
        {
            DirectoryInfo[] dirs = dir.GetDirectories();

            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                if (file.Name.Contains("something"))
                {
                    //do something.... xD
                }
            }

            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    //string temppath = Path.Combine(destDirName, subdir.Name);
                    searchDirectory(subdir.FullName, doSubdirs);
                }
            }
        }
        catch (UnauthorizedAccessException)
        { }