Path.Combine Absolute with Relative Path Strings

C# combining absolute and relative paths, Path.GetFullPath() inconsistent

Based on the MSDN Documentation, this is expected behavior.

If path2 does not include a root (for example, if path2 does not start
with a separator character or a drive specification), the result is a
concatenation of the two paths, with an intervening separator
character. If path2 includes a root, path2 is returned.

Seperator characters are discussed in this MSDN article.

So let's take a look at your test cases:

var test1 = Path.GetFullPath(Path.Combine(@"C:\users\dev\desktop\testfiles\", @".\test1.txt"));
var test2 = Path.GetFullPath(Path.Combine(@"C:\users\dev\desktop\testfiles\", @"\test2.txt"));

Test1 is behaving correctly because it is taking the . as part of a valid file path and using it in combination with the first parameter to generate the combined path.

Test2 is behaving as expected because the \ is a separator character, so as described it is returned without the first parameter.

Path.Combine two relative path strings to create new relative path

Try this:

Path.GetFullPath(Path.Combine(path1, path2))
.Substring(Directory.GetCurrentDirectory().Length + 1);

Combine an absolute path with a relative path

Try this:

string abs = "X:/A/B/Q";
string rel = "../../B/W";
var path = Path.GetFullPath(Path.Combine(abs,rel));

It will give you full absolute path
http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx

Why does Path.Combine produce this result with a relative path?

Drop the leading slash on relativePath and it should work.

The reason why this happens is that Path.Combine is interpreting relativePath as a rooted (absolute) path because, in this case, it begins with a \. You can check if a path is relative or rooted by using Path.IsRooted().

From the doc:

If the one of the subsequent paths is
an absolute path, then the combine
operation resets starting with that
absolute path, discarding all previous
combined paths.

C# Combining two relative network paths

The issue appears to be that .NET (and maybe Windows) does not view the parent of \\server1\customers to be \\server.

It looks like technically \\server is not a valid UNC path (i.e. you can't store files there directly).

var thisWorks = Directory.GetParent(Dir);

var thisIsNull = Directory.GetParent(Directory.GetParent(Dir).FullName);

Thus when you ask for ..\\..\\ it effectively ignores one of them since it deduces it can't go any higher up the directory tree...

Combine absolute path and relative path to get a new absolute path

The path.Join when used with path.Dir should do what you want. See http://golang.org/pkg/path/#example_Join for an interactive example.

path.Join(path.Dir("/help/help1.html"), "../content.txt")

This will return /content.txt.



Related Topics



Leave a reply



Submit