C# 4.0 需要一个在C中搜索所有C驱动器的目录的方法吗#
我需要在文件系统中找到一个名为“GameData”的文件夹,它通常存储在程序文件中,但如果不是,我希望能够找到它,无论它在C驱动器中的什么位置 目前,我正在使用:C# 4.0 需要一个在C中搜索所有C驱动器的目录的方法吗#,c#-4.0,exception-handling,directory,C# 4.0,Exception Handling,Directory,我需要在文件系统中找到一个名为“GameData”的文件夹,它通常存储在程序文件中,但如果不是,我希望能够找到它,无论它在C驱动器中的什么位置 目前,我正在使用: IEnumerable<string> list = Directory.GetDirectories(root, "GameData", SearchOption.AllDirectories); IEnumerable list=Directory.GetDirectories(root,“GameData”,Sea
IEnumerable<string> list = Directory.GetDirectories(root, "GameData", SearchOption.AllDirectories);
IEnumerable list=Directory.GetDirectories(root,“GameData”,SearchOption.AllDirectories);
但当它试图在受保护的目录中导航时,会抛出一个UnauthorizedAccessException
我是否可以添加一些东西来阻止它尝试访问任何受保护的目录?异常发生后,try/catch
块是否允许继续搜索
编辑
注意:我不是在寻找一个特定的文件,而是一个名为GameData的文件夹,这样我就可以使用该位置作为.zip提取的输出,或者读取其中文件夹的名称。您可以选中:
目录对象的GetDirectories
和GetFiles
方法是递归搜索与搜索字符串匹配的文件所需的全部。以下方法用于执行递归:
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, txtFile.Text))
{
lstFilesFound.Items.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
您需要使用递归方法,而不是
AllDirectories
。然后可以跳过导致异常的目录
“使用SearchOption.AllDirectories
的缺点是,如果指定根目录下的任何一个子目录导致DirectoryNotFoundException
或UnauthorizedAccessException
,则整个方法将失败,并且不会返回任何目录。使用GetFiles
方法时也是如此。如果必须处理特定子文件夹上的这些异常,则必须手动遍历目录树“
也许有更好的方法找到该文件夹?请记住,整个文件系统中可能有多个
GameData
目录。搜索整个文件系统可能需要一段时间……您是否在安装的应用程序中查找文件夹?我有一个名为“GameData”的文件夹“我把我所有的宠物鱼照片和一些重要的文件都放在这里。。。希望您的软件不会将其丢弃;-)这些文件与我无关,所以我会删除最里面的for循环并使用类似于Directory.getdirecotrys(d,“GameData”)代码>取而代之?@sh3rime:-你可以试试!所以,当我在桌面上使用它时,它可以工作,但如果我只在C上使用它,它就会失败。这有什么原因吗?
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);
}
}
}