如何从基本路径和包含“..”的相对路径获取绝对文件路径?

发布于 2024-09-07 14:48:57 字数 320 浏览 2 评论 0原文

string basepath = @"C:\somefolder\subfolder\bin"; // is defined in runtime
string relative = @"..\..\templates";

string absolute = Magic(basepath, relative); // should be "C:\somefolder\templates"

你能帮我使用Magic方法吗?希望代码不要太复杂。

.NET Framework 中有“Magic”方法吗?

string basepath = @"C:\somefolder\subfolder\bin"; // is defined in runtime
string relative = @"..\..\templates";

string absolute = Magic(basepath, relative); // should be "C:\somefolder\templates"

Can you help me with Magic method? Hopefully not too complicated code.

Is there the "Magic" method in .NET Framework?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

メ斷腸人バ 2024-09-14 14:48:57

如果您查看路径 类有几个方法应该有帮助:

Path.Combine

所以

Path.GetFullPath

string newPath = Path.Combine(basepath, relative);
string absolute = Path.GetFullPath(newPath);

虽然第二步并不是严格需要的 - 如果您打印出来的话,它会给您一个“更干净”的路径。

If you look at the Path class there are a couple of methods which should help:

Path.Combine

and

Path.GetFullPath

So:

string newPath = Path.Combine(basepath, relative);
string absolute = Path.GetFullPath(newPath);

Although the second step isn't strictly needed - it would give you a "cleaner" path if you were printing out say.

掌心的温暖 2024-09-14 14:48:57

因为 Path.Combine 并非在所有情况下都有效,这里有一个更复杂的函数:-)

static string GetFullPath(string maybeRelativePath, string baseDirectory) {
    if (baseDirectory == null) baseDirectory = Environment.CurrentDirectory;
    var root = Path.GetPathRoot(maybeRelativePath);
    if (string.IsNullOrEmpty(root)) 
        return Path.GetFullPath(Path.Combine(baseDirectory, maybeRelativePath));
    if (root == "\\") 
        return Path.GetFullPath(Path.Combine(Path.GetPathRoot(baseDirectory), maybeRelativePath.Remove(0, 1)));
    return maybeRelativePath;
}

Path.Combine(@"C:\foo\",@"\foo\bar") 返回 @"\foo\bar" 而不是预期的 @"C:\foo\bar"

Because Path.Combine does not work in all cases here is a more complex function :-)

static string GetFullPath(string maybeRelativePath, string baseDirectory) {
    if (baseDirectory == null) baseDirectory = Environment.CurrentDirectory;
    var root = Path.GetPathRoot(maybeRelativePath);
    if (string.IsNullOrEmpty(root)) 
        return Path.GetFullPath(Path.Combine(baseDirectory, maybeRelativePath));
    if (root == "\\") 
        return Path.GetFullPath(Path.Combine(Path.GetPathRoot(baseDirectory), maybeRelativePath.Remove(0, 1)));
    return maybeRelativePath;
}

Path.Combine(@"C:\foo\",@"\foo\bar") returns @"\foo\bar" and not as expected @"C:\foo\bar"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文