2014-09-21 50 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; 
} 
..... 
相关问题