gpt4 book ai didi

c# - 如何防止Directory.GetFiles到 "check"回收站等 "unsafe"地方?

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:40 26 4
gpt4 key购买 nike

伙计们,我在我的应用程序中有一个功能,可以使用 GetFiles 在特定目录中搜​​索特定文件。方法

System.IO.Directory.GetFiles(string path, string searchPattern, System.IO.SearchOption)

它工作正常,直到我选择要搜索的驱动器目录(D:\C:\ 等),因为它也在访问回收站,然后限制

Access to the path 'D:\$RECYCLE.BIN\S-1-5-21-106145493-3722843178-2978326776-1010' is denied.

它还需要能够搜索子文件夹 (SearchOption.AllDirectories)。

如何跳过要搜索的地方?因为可能还有任何其他文件夹也被拒绝访问。

我将 SKIP 大写,因为如果我使用 try catch 并捕获到一个异常,那么整个搜索也会失败。

谢谢。请澄清您需要的任何内容。

最佳答案

已编辑以更加清晰。

当递归扫描目录树时,比如使用递归方法,以目录开始作为参数,你可以得到目录的属性。然后检查它是否是系统目录而不是像“C:\”这样的根目录 - 在这种情况下,您想要跳过该目录,因为它可能是,例如,回收站。

这是执行此操作的一些代码,还捕获了一些在我摆弄目录扫描时发生的常见异常。

void    scan_dir(string path)
{
// Exclude some directories according to their attributes
string[] files = null;
string skipReason = null;
var dirInfo = new DirectoryInfo( path );
var isroot = dirInfo.Root.FullName.Equals( dirInfo.FullName );
if ( // as root dirs (e.g. "C:\") apparently have the system + hidden flags set, we must check whether it's a root dir, if it is, we do NOT skip it even though those attributes are present
(dirInfo.Attributes.HasFlag( FileAttributes.System ) && !isroot) // We must not access such folders/files, or this crashes with UnauthorizedAccessException on folders like $RECYCLE.BIN
)
{ skipReason = "system file/folder, no access";
}

if ( null == skipReason )
{ try
{ files = Directory.GetFiles( path );
}
catch (UnauthorizedAccessException ex)
{ skipReason = ex.Message;
}
catch (PathTooLongException ex)
{ skipReason = ex.Message;
}
}

if (null != skipReason)
{ // perhaps do some error logging, stating skipReason
return; // we skip this directory
}

foreach (var f in files)
{ var fileAttribs = new FileInfo( f ).Attributes;
// do stuff with file if the attributes are to your liking
}

try
{ var dirs = Directory.GetDirectories( path );
foreach (var d in dirs)
{ scan_dir( d ); // recursive call
}
}
catch (PathTooLongException ex)
{ Trace.WriteLine(ex.Message);
}
}

关于c# - 如何防止Directory.GetFiles到 "check"回收站等 "unsafe"地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27010203/

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