gpt4 book ai didi

c# - 访问路径 'd:\$RECYCLE.BIN\S-1-5-21-494745725-312220573-749543506-41600' 被拒绝

转载 作者:太空狗 更新时间:2023-10-29 23:29:45 24 4
gpt4 key购买 nike

我是 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
}
}

请帮我解决一下。谢谢

最佳答案

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

Do NOT use 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, "*");

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

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

如果在获得所有可访问目录后有一些您特别想避免的目录,您还可以通过 LINQ 使用部分目录名称作为关键字(即回收站)。

关于c# - 访问路径 'd:\$RECYCLE.BIN\S-1-5-21-494745725-312220573-749543506-41600' 被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34525090/

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