如何在 .NET 中获得绝对或规范化的文件路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1266674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:08:28  来源:igfitidea点击:

How can one get an absolute or normalized file path in .NET?

.netfilepath

提问by mark

How can one with minimal effort (using some already existing facility, if possible) convert paths like c:\aaa\bbb\..\cccto c:\aaa\ccc?

如何以最小的努力(如果可能的话,使用一些现有的设施)将路径转换c:\aaa\bbb\..\cccc:\aaa\ccc

回答by nawfal

I would write it like this:

我会这样写:

public static string NormalizePath(string path)
{
    return Path.GetFullPath(new Uri(path).LocalPath)
               .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
               .ToUpperInvariant();
}

This should handle few scenarios like

这应该处理一些场景,比如

  1. uri and potential escaped characters in it, like

    file:///C:/Test%20Project.exe -> C:\TEST PROJECT.EXE

  2. path segments specified by dots to denote current or parent directory

    c:\aaa\bbb\..\ccc -> C:\AAA\CCC

  3. tilde shortened (long) paths

    C:\Progra~1\ -> C:\PROGRAM FILES

  4. inconsistent directory delimiter character

    C:/Documents\abc.txt -> C:\DOCUMENTS\ABC.TXT

  1. uri 和其中的潜在转义字符,例如

    file:///C:/Test%20Project.exe -> C:\TEST PROJECT.EXE

  2. 由点指定的路径段表示当前或父目录

    c:\aaa\bbb\..\ccc -> C:\AAA\CCC

  3. 波浪号缩短(长)路径

    C:\Progra~1\ -> C:\PROGRAM 文件

  4. 不一致的目录分隔符

    C:/Documents\abc.txt -> C:\DOCUMENTS\ABC.TXT

Other than those, it can ignore case, trailing \directory delimiter character etc.

除此之外,它可以忽略大小写、尾随\目录分隔符等。

回答by leppie

Path.GetFullPathperhaps?

Path.GetFullPath也许?

回答by bdukes

Canonicalization is one of the main responsibilities of the Uriclass in .NET.

规范化是.NET 中Uri类的主要职责之一。

var path = @"c:\aaa\bbb\..\ccc";
var canonicalPath = new Uri(path).LocalPath; // c:\aaa\ccc