根据this MSDN article,Directory.Exists可以返回错误的否定结果(该目录存在,但不能读取或类似)。我想知道是否有类似的方法,而不是返回真或假,返回更多的信息...像“访问被拒绝”或“路径太长”...可靠的Directory.Exists using C#
0
A
回答
1
你可以尝试创建一个DirectoryInfo
对象。如果路径无效或用户无权访问,构造函数应该会引发异常。你仍然需要检查它是否存在。
try
{
var di = new DirectoryInfo(path);
if(di.Exists)
{
//The directory exists
}
else
{
//The path is valid, but does not exist.
}
}
catch(Exception e)
{
//The path is invalid or user does not have access.
}
1
有一个Directory.GetAccessControl()
方法,你可以用它来获得可列,但无法读取目录:
public static bool DirectoryVisible(string path)
{
try
{
Directory.GetAccessControl(path);
return true;
}
catch (UnauthorizedAccessException)
{
return true;
}
catch
{
return false;
}
}
您也可以利用DirectoryInfo
类。它配备了Exists
财产和Attributes
财产。如果在访问Attributes
属性时抛出了UnauthorizedAccessException
,则表示您无法访问该目录。
0
这个代码可以,如果一个文件实际上存在区分,而如果该文件,但用户不能访问从源头
enum ExistState { exist, notExist, inaccessible };
void Check(string name) {
DirectoryInfo di = new DirectoryInfo(name);
ExistState state = ExistState.exist;
if (!di.Exists) {
try {
if ((int)di.Attributes == -1) {
state = ExistState.notExist;
}
} catch (UnauthorizedAccessException) {
state = ExistState.inaccessible;
}
}
Console.WriteLine("{0} {1}", name, state);
}
解释
“的DirectoryInfo.Attributes属性记录不正确,并且不会引发FileNotFound或DirectoryNotFound异常,而是从基础win api函数返回错误值,该值为0xFFFFFFFF或-1。
如果路径存在但访问不被允许,则尝试检索属性将引发异常。
如果路径不存在,那么该属性将是-1。”
相关问题
- 1. C#Directory.Exists
- 2. C#Directory.Exists ipv6版本
- 3. c#可靠MouseMove(hop)
- 4. c中可靠的udp#
- 5. Directory.Exists - 拒绝访问的UNC路径C#
- 6. Casting using System.Type - c#
- 7. Libcurl using C
- 8. CopyFiles using IFileOperation(C++)
- 9. C#using System.Data.Metadata.Edm
- 10. Hadoop Streaming using C
- 11. 可靠组播库C++
- 12. Directory.Exists在ASP.NET
- 13. 我可以依靠using语句来关闭我的MySQL连接吗?
- 14. C++:using namespace and #include
- 15. Link curl using codelite C++
- 16. C#SendGrid using-direktive missing
- 17. 简单可靠的UDP C++库
- 18. 可靠的C语境窗口
- 19. C#模式匹配的可靠途径?
- 20. 范围的C++ using指令
- 21. Directory.Exists(文件)不工作
- 22. Directory.Exists敏感的时间?
- 23. Directory.Exists()奇怪的行为
- 24. Java可靠的UDP
- 25. iBeacon靠近不可靠
- 26. Qpid可靠性
- 27. Xeround可靠性
- 28. Directory.Exists()总是返回false?
- 29. aspnet c#form submision using javascript
- 30. c#.net using asp:CompareValidator with dates
我不认为这是真的,'DirectoryInfo'构造函数抛出的异常的不存在或您穿上”路径至少,它并没有在我刚刚跑过的一个快速测试中,噢,但我现在看到你说的是一条真正无效的路径,而不是一条不存在的路径,但那么测试有什么好处对于OP? – adv12
@ adv12检查MSDN文档的链接,你仍然需要检查它是否存在,正如我提到的 – juharr
哦,我发现OP想要捕获像“path too long”这样的错误,由该构造函数。 – adv12