gpt4 book ai didi

c# - 如何检查对字符串路径的访问是否被拒绝?

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

我想知道如何测试我是否可以访问字符串路径。这是我使用的代码:

using System;
using System.IO;

namescpace prog1
{
class Program
{
static void Main(string[] args)
{
string path = @"C:\Users\Admin";
DirectoryInfo dir = new DirectoryInfo(path);
foreach (FileInfo fil in dir.GetFiles())
{
//At dir.GetFiles, I get an error saying
//access to the string path is denied.

Console.WriteLine(fil.Name);
}
Console.ReadLine();
}
}
}

我想测试访问是否被拒绝(到字符串路径)然后执行 GetFiles 等等。

我已经找到了:how can you easily check if access is denied for a file in .NET?

有什么帮助吗?

最佳答案

最简单(通常也是最安全)的选择是只做您现在正在做的事情,但将代码包装在适当的异常处理中。

然后您可以捕获 UnauthorizedAccessException来自 GetFiles(并且可能是来自 DirectoryInfo 构造函数的 SecurityException,具体取决于路径),并将您的处理逻辑放在那里。

关于c# - 如何检查对字符串路径的访问是否被拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9794313/

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