根據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