问题
I'm trying to join a Windows path with a relative path using Path.Combine.
However, Path.Combine(@"C:\blah",@"..\bling")
returns C:\blah\..\bling
instead of C:\bling\
.
Does anyone know how to accomplish this without writing my own relative path resolver (which shouldn't be too hard)?
回答1:
What Works:
string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);
(result: absolutePath="C:\bling.txt")
What doesn't work
string relativePath = "..\\bling.txt";
Uri baseAbsoluteUri = new Uri("C:\\blah\\");
string absolutePath = new Uri(baseAbsoluteUri, relativePath).AbsolutePath;
(result: absolutePath="C:/blah/bling.txt")
回答2:
Call Path.GetFullPath on the combined path http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
> Path.GetFullPath(Path.Combine(@"C:\blah\",@"..\bling"))
C:\bling
(I agree Path.Combine ought to do this by itself)
回答3:
Path.GetFullPath(@"c:\windows\temp\..\system32")?
回答4:
This will give you exactly what you need (path does NOT have to exist for this to work)
DirectoryInfo di = new DirectoryInfo(@"C:\blah\..\bling");
string cleanPath = di.FullName;
回答5:
For windows universal apps Path.GetFullPath()
is not available, you can use the System.Uri
class instead:
Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));
Console.WriteLine(uri.LocalPath);
回答6:
Be careful with Backslashes, don't forget them (neither use twice:)
string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
//OR:
//string relativePath = "\\..\\bling.txt";
//string baseDirectory = "C:\\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);
来源:https://stackoverflow.com/questions/670566/path-combine-absolute-with-relative-path-strings