下面的Function是为了检查File/Directory路径是否存在而写的,旁边还有检索Function检查的最后一条路径的RecentPath。
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总是在调用函数时检索已设置的路径,而不是最终路径。
示例:
假设我需要检查/user目录是否存在于myDocument中,然后得到最近检查过的路径,因此:
Path.Exists("/user", 2);
MessageBox.Show(Path.RecentPath);输出应该是C:\Users\Hossam\Documents\user\,但它只是/user。
发布于 2014-09-21 21:43:03
输入字符串开头的斜杠(/)显然会干扰Path.Combine()。试试这个:
Path.Exists("user", 2);
MessageBox.Show(Path.RecentPath);输出:C:\Users\Hossam\Documents\user
发布于 2014-09-21 22:00:09
之所以会发生这种情况,是因为您传递了一个以正斜杠开头的字符串。
在Windows系统中,这是AltDirectorySeparatorChar
在Path.Combine文档中,您可以阅读以下注释
如果path2不包括根(例如,如果path2不以分隔符或驱动器规范开头),则结果是两个路径的连接,并带有中间分隔符。如果path2包含根,则返回path2。
现在查看Path.Combine的源代码,您可以看到
.....
if (IsPathRooted(path2))
{
return path2;
}
....当然,IsPathRooted包含
.....
if (path[0] == AltDirectorySeparatorChar)
{
return true;
}
.....https://stackoverflow.com/questions/25964081
复制相似问题