开发者

Path.Combine and the dot notation [duplicate]

This question already has answers here: Path.Combine absolute with relative path strings (7 answers) 开发者_高级运维 Closed 6 years ago.

I'm looking for something akin to Path.Combine method that will help me correctly combine absolute and relative paths. For example, I want

Path.Combine(@"c:\alpha\beta", @"..\gamma");

to yield c:\alpha\gamma instead of c:\alpha\..\gamma as Path.Combine does. Is there any easy way of accomplishing this? Needless to say, I also want to period . path or multiple .. paths (e.g., ..\..\) to work correctly.


Use Path.GetFullPath

string path = Path.Combine(@"c:\alpha\beta", @"..\gamma");
Console.WriteLine(Path.GetFullPath(path));

or the DirectoryInfo class:

string path = Path.Combine(@"c:\alpha\beta", @"..\gamma");
DirectoryInfo info = new DirectoryInfo(path);
Console.WriteLine(info.FullName);

Both will output:

c:\alpha\gamma


You can probably do a Path.Combine followed by a Path.GetFullPath.


you could use a combination of 2 calls like so:

string path = Path.Combine(@"c:\alpha\beta", @"..\gamma");
string result = Path.GetFullPath(path);

And that should give you the results you're looking for.


You can call Path.GetFullPath to resolve this.

For example, this code:

string path = Path.Combine(@"c:\alpha\beta", @"..\gamma");
Console.WriteLine(path); 
path = Path.GetFullPath(path);
Console.WriteLine(path);

Will print:

c:\alpha\beta\..\gamma
c:\alpha\gamma


But it seems GetFullPath is not always right Try:

  Console.WriteLine(System.IO.Path.GetFullPath(@"\\machine\sharea\foldera\..\shareb\folderb"));
  Console.WriteLine(System.IO.Path.GetFullPath(@"\\machine\sharea\foldera\..\..\shareb\folderb"));

They output the same result, seems you cannot move it to go to a different share The correct answer for the second one should be

\\machinea\shareb\folderb

but it gives

\\machinea\sharea\shareb\folderb

for both

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜