gpt4 book ai didi

c#-4.0 - 需要一种在 C# 中搜索所有 C 驱动器目录的方法

转载 作者:行者123 更新时间:2023-12-01 23:59:25 24 4
gpt4 key购买 nike

我需要在文件系统中找到一个名为“GameData”的文件夹,它通常存储在 Program Files 中,但如果不是,我希望能够找到它,无论它在 C 盘中的哪个位置。

目前,我正在使用:

IEnumerable<string> list = Directory.GetDirectories(root, "GameData", SearchOption.AllDirectories);

但它会抛出一个 UnauthorizedAccessException,这是预期的,因为它试图在 protected 目录中导航。

我是否可以添加一些东西来阻止它尝试访问任何 protected 目录? try/catch block 是否允许在异常发生后继续搜索?

编辑

注意:我不是在寻找特定文件,只是在寻找名为 GameData 的文件夹,这样我就可以将该位置用作 .zip 提取的输出,或读取其中文件夹的名称。

最佳答案

您需要使用递归方法而不是 AllDirectories。然后你可以跳过导致异常的目录。

MSDN: Iterate Through a Directory Tree (C# Programming Guide)

“使用 SearchOption.AllDirectories 的弱点在于,如果指定根目录下的任何一个子目录导致 DirectoryNotFoundExceptionUnauthorizedAccessException,整个方法失败并且不返回任何目录。当您使用 GetFiles 方法时也是如此。如果您必须在特定子文件夹上处理这些异常,则必须手动遍历目录树”

static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;

// First, process all the files directly under this folder
try
{
files = root.GetFiles("*.*");
}
// This is thrown if even one of the files requires permissions greater
// than the application provides.
catch (UnauthorizedAccessException e)
{
// This code just writes out the message and continues to recurse.
// You may decide to do something different here. For example, you
// can try to elevate your privileges and access the file again.
log.Add(e.Message);
}

catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}

if (files != null)
{
foreach (System.IO.FileInfo fi in files)
{
// In this example, we only access the existing FileInfo object. If we
// want to open, delete or modify the file, then
// a try-catch block is required here to handle the case
// where the file has been deleted since the call to TraverseTree().
Console.WriteLine(fi.FullName);
}

// Now find all the subdirectories under this directory.
subDirs = root.GetDirectories();

foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
// Resursive call for each subdirectory.
WalkDirectoryTree(dirInfo);
}
}
}

关于c#-4.0 - 需要一种在 C# 中搜索所有 C 驱动器目录的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22223665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com