2016-11-04 146 views
0

給定一個路徑(可能是相對的),我如何能夠檢查路徑是目錄,還是GUID或文件。它們可能不存在,這使得我很難找出解決方案。C#檢查相對路徑是否是目錄或GUID或文件

我以前的解決方案是檢查路徑是像這樣的擴展:

public bool IsDirectory(string path) 
    { 
     var extension = Path.GetExtension(path); 

     return string.IsNullOrEmpty(extension); 
    } 

但我發現,這條路徑通常會也是一個GUID的路徑,所以上面會是不正確的。

有沒有更好的方法我可以寫一個函數來檢查所有這些情況?

+3

'檢查路徑是一個目錄,或GUID,或file'這些東西是不喜歡別人一個 – Jonesopolis

+1

你說,有時候你不得不說是剛剛的GUID沒有擴展名的文件名?因爲路徑是文件或目錄,並且不清楚Guids如何與路徑相關。 – juharr

+1

此鏈接可能會幫助你:[http://stackoverflow.com/questions/1395205/better-way-to-check-if-a-path-is-a-file-or-a-directory](http:/ /stackoverflow.com/questions/1395205/better-way-to-check-if-a-path-is-a-file-or-a-directory) – Kymuweb

回答

3

這將檢查它的文件或路徑,如果它不是我們試圖解析它的GUID。

if(File.Exists(path)) 
{ 
    FileAttributes attr = File.GetAttributes(path); 

    if (attr.HasFlag(FileAttributes.Directory)) 
     MessageBox.Show("Its a directory"); 
    else 
     MessageBox.Show("Its a file"); 
} 
else 
{ 
    Guid guid; 

    if (Guid.TryParse(path, out guid)) 
     MessageBox.Show("Its a Guid"); 
} 
相關問題