Unexpected behavior from path.combine
.net, c#
Solution
Why is this method designed to consider a single \ a root?
Because it is a root as far as other operations are concerned. For example, on the command prompt:
c:\Users\Jon\Test>dir \
Volume in drive C is Windows8_OS
Volume Serial Number is C058-6ADE
Directory of c:\
Or from other file operations in .NET:
using System;
using System.IO;
class Test
{
static void Main()
{
var lines = File.ReadAllLines(@"\Users\Jon\Test\Test.cs");
Console.WriteLine(lines.Length);
}
}
Output:
11
Or from Java:
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
String path = "\\Users\\Jon\\Test\\Test.java";
// Just to prove that the double backslashes are language escapes...
System.out.println(path);
// Obviously we'd normally clean stuff up...
InputStream stream = new FileInputStream(path);
BufferedReader reader = new BufferedReader
(new InputStreamReader(stream, "utf-8"));
System.out.println(reader.readLine());
}
}
Output:
\Users\Jon\Test\Test.java
import java.io.*;
I dare say the same would be true from native code.
So, where doesn't Windows allow you to start a path with a "\" to root it within the current drive?
Why is this method designed to consider a single \ a root?
I think the bigger question is why you started what you wanted to be a relative path with a `\`.
Problem
Given the code: ``` string p = @"C:\Users\Brian"; string p2 = @"\bin\Debug"; string result = Path.Combine(p, p2);//result: \bin\Debug Console.WriteLine(result); ``` I expect to see a result of: ``` C:\Users\Brian\bin\Debug ``` However the result is ``` \bin\Debug ``` If I initialize `p2 = @"bin\Debug";` Then the result is as expected. Looking at MSDN this appears to work as designed: 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. IMO, it makes far more sense in .NET to exclude `\` as a root. AFAIK, this is not a valid root on any windows OS (`\\` can be). I could then combine partial paths without concern over whether a partial path begins with a `\`. Why is this method designed to consider a single `\` a root?