2014-09-21 25 views
1

下面我寫Function檢查是否存在File/Directory路徑,還有RecentPath,它檢索Function檢查過的最後一條路徑。爲什麼函數輸出錯誤的值?

private static String IRecentPath; 
    public static String RecentPath 
    { 
     get 
     { 
      return IRecentPath; 
     } 
    } 

    public static Boolean Exists(String Path, Int32 PathType = 0) 
    { 
     return Exist(Path, PathType); 
    } 

    internal static Boolean Exist(String Path, Int32 PathType = 0) 
    { 
     Boolean Report = false; 
     switch (PathType) 
     { 
      case 0: 
       Report = (Directory.Exists(Path) || File.Exists(Path)); 
       IRecentPath = Path; 
       break; 
      case 1: 
       String MPath = AppDomain.CurrentDomain.BaseDirectory; 
       Report = (Directory.Exists(System.IO.Path.Combine(MPath, Path)) || File.Exists(System.IO.Path.Combine(MPath, Path))); 
       IRecentPath = System.IO.Path.Combine(MPath, Path); 
       break; 
      case 2: 
       String LPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
       Report = (Directory.Exists(System.IO.Path.Combine(LPath, Path)) || File.Exists(System.IO.Path.Combine(LPath, Path))); 
       IRecentPath = System.IO.Path.Combine(LPath, Path); 
       break; 
      default: 
       break; 
     } 
     return Report; 
    } 

的問題是,RecentPath總是檢索,同時調用該函數,而不是最終的路徑已設置的路徑。

例子:

比方說,我需要檢查,如果在myDocument存在/user目錄,然後讓已檢查了最後的最近路徑,因此:

Path.Exists("/user", 2); 
MessageBox.Show(Path.RecentPath); 

輸出應該是C:\Users\Hossam\Documents\user\但相反,它只是/user

回答

3

輸入字符串開頭的斜槓(/)顯然會干擾Path.Combine()。試試這個:

Path.Exists("user", 2); 
MessageBox.Show(Path.RecentPath); 

輸出:C:\Users\Hossam\Documents\user

+0

喔上帝就是這樣(Y)的感謝。 – Enumy 2014-09-21 21:46:00

+2

「干擾」可能不是一個正確的詞。這基本上是IO.Path.Combine的工作原理 - 它看到第二個參數以分隔符開始,顯然假定它已經在根目錄,並且只輸出第二個路徑。有關詳細信息,請參見[MSDN](http://msdn.microsoft.com/zh-cn/library/fyy7a5kt%28v=vs.110%29.aspx)。 – Andrei 2014-09-21 21:46:16

+0

@Andrei我知道它應該和這就是爲什麼它從來沒有出現在我的腦海裏,那是問題所在,但不知何故,當我只用'「用戶」'它工作正常!!? – Enumy 2014-09-21 21:48:44

3

這是因爲你通過與正斜槓開頭的字符串。
在Windows系統中,這是AltDirectorySeparatorChar

Path.Combine文檔,你可以閱讀這句話

如果PATH2不包括根目錄(例如,如果PATH2不以分隔符開始 或一個驅動器規範),結果是兩條路徑連接在一起,其間插入了一個分隔符 字符。 如果path2包含一個根,則返回path2。

現在看看Path.Combine的源代碼,你可以看到

..... 
if (IsPathRooted(path2)) 
{ 
    return path2; 
} 
.... 

當然IsPathRooted包含

..... 
if (path[0] == AltDirectorySeparatorChar) 
{ 
    return true; 
} 
.....