0

I want to make sure that path always ends with \ and I try to use Path.Combine as the code below.

I expect System.IO.Path.Combine("xxx", System.IO.Path.DirectorySeparatorChar.ToString()) to return xxx\ but it returns only \

The same goes for System.IO.Path.Combine("xxx", "\\", "zz") which I expect xxx\zz but it turns out to be \zz

Here are tests I have done. enter image description here

I am not sure if this is a desired behavior or it's a bug.

Anonymous
  • 9,366
  • 22
  • 83
  • 133

4 Answers4

5

This is defined behaviour of Path.Combine. If the second (or any subsequent) path is "rooted", i.e. starts with a path delimiter like '\' or 'c:', any previous parameters are ignored. From the documentation:

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.

You should not use things like System.IO.Path.DirectorySeparatorChar when using Path.Combine, IMHO, it's whole point of being is to make path manipulation easier, not harder.

SWeko
  • 30,434
  • 10
  • 71
  • 106
1

Path.Combine combines paths. If the second parameter is a relative path, the paths are combined; if it is an absolute path, only the second parameter is returned (since combining absolute paths does not make sense). \ is an absolute path referring to the root directory.

What you want can more easily be achieved by

myPath = myPath.TrimEnd('\') + "\";

On the other hand, why do you need your path to end with a \? The whole point of Path.Combine is that you don't need to have paths ending with \. Note the following examples:

myPath = Path.Combine(@"C:\xxx", "zz");    // yields C:\xxx\zz
myPath = Path.Combine(@"C:\xxx\", "zz");   // also yields C:\xxx\zz
Heinzi
  • 167,459
  • 57
  • 363
  • 519
0

From the documentation for Combine:

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.

Since \ is an absolute path, everything preceding it is discarded.

Gabe
  • 84,912
  • 12
  • 139
  • 238
0

It's documented behaviour. From the documentation for Path.Combine(string path1, string path2):

If path2 contains an absolute path, this method returns path2.

Joe
  • 122,218
  • 32
  • 205
  • 338