首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么函数输出值错误?

为什么函数输出值错误?
EN

Stack Overflow用户
提问于 2014-09-21 21:32:20
回答 2查看 67关注 0票数 1

下面的Function是为了检查File/Directory路径是否存在而写的,旁边还有检索Function检查的最后一条路径的RecentPath

代码语言:javascript
复制
    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中,然后得到最近检查过的路径,因此:

代码语言:javascript
复制
Path.Exists("/user", 2);
MessageBox.Show(Path.RecentPath);

输出应该是C:\Users\Hossam\Documents\user\,但它只是/user

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-09-21 21:43:03

输入字符串开头的斜杠(/)显然会干扰Path.Combine()。试试这个:

代码语言:javascript
复制
Path.Exists("user", 2);
MessageBox.Show(Path.RecentPath);

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

票数 3
EN

Stack Overflow用户

发布于 2014-09-21 22:00:09

之所以会发生这种情况,是因为您传递了一个以正斜杠开头的字符串。

在Windows系统中,这是AltDirectorySeparatorChar

Path.Combine文档中,您可以阅读以下注释

如果path2不包括根(例如,如果path2不以分隔符或驱动器规范开头),则结果是两个路径的连接,并带有中间分隔符。如果path2包含根,则返回path2。

现在查看Path.Combine的源代码,您可以看到

代码语言:javascript
复制
.....
if (IsPathRooted(path2))
{
    return path2;
}
....

当然,IsPathRooted包含

代码语言:javascript
复制
.....
if (path[0] == AltDirectorySeparatorChar)
{
    return true;
}
.....
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25964081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档