如何在 .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
How can one get an absolute or normalized file path in .NET?
提问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\..\ccc为c:\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
这应该处理一些场景,比如
uri and potential escaped characters in it, like
file:///C:/Test%20Project.exe -> C:\TEST PROJECT.EXE
path segments specified by dots to denote current or parent directory
c:\aaa\bbb\..\ccc -> C:\AAA\CCC
tilde shortened (long) paths
C:\Progra~1\ -> C:\PROGRAM FILES
inconsistent directory delimiter character
C:/Documents\abc.txt -> C:\DOCUMENTS\ABC.TXT
uri 和其中的潜在转义字符,例如
file:///C:/Test%20Project.exe -> C:\TEST PROJECT.EXE
由点指定的路径段表示当前或父目录
c:\aaa\bbb\..\ccc -> C:\AAA\CCC
波浪号缩短(长)路径
C:\Progra~1\ -> C:\PROGRAM 文件
不一致的目录分隔符
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也许?

