[英]How do I check if an access to a string path is denied?
i want to know how i can test if i can access a string path or not. 我想知道如何测试是否可以访问字符串路径。 Here is the code I use:
这是我使用的代码:
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();
}
}
}
I want to test if acces is denied (to string path) Then do the GetFiles and all that. 我想测试acces是否被拒绝(到字符串路径),然后执行GetFiles等。
I've already found this: how can you easily check if access is denied for a file in .NET? 我已经发现了这一点: 如何轻松检查.NET中文件的访问是否被拒绝?
Any help? 有什么帮助吗?
The simplest (and usually safest) option is to just do what you're doing now, but wrap the code in proper exception handling. 最简单(通常也是最安全)的方法是只做您现在正在做的事情,但是将代码包装在适当的异常处理中。
You can then catch the UnauthorizedAccessException from GetFiles
(and potentially a SecurityException
from the DirectoryInfo
constructor, depending on the path) explicitly, and put your handling logic there. 然后,您可以显式捕获
GetFiles
的UnauthorizedAccessException (以及可能从DirectoryInfo
构造函数中获取SecurityException
,具体取决于路径),并将处理逻辑放在此处。
Can do something like this: 可以做这样的事情:
static void Main(string[] args)
{
string path = @"C:\Users\Admin";
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] files = null;
try {
files = dir.GetFiles();
}
catch (UnauthorizedAccessException ex) {
// do something and return
return;
}
//else continue
foreach (FileInfo fil in files )
{
//At dir.GetFiles, I get an error saying
//access to the string path is denied.
Console.WriteLine(fil.Name);
}
Console.ReadLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.