Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using Path.Combine over concatenating strings with '+'?

I don't quite see the difference.

What could Path.Combine do better than perfectly working string concatenation?

I guess it's doing something very similar in the background.

Can anyone tell me why it is so often preferred?

like image 950
Sossenbinder Avatar asked Aug 18 '15 11:08

Sossenbinder


People also ask

Why use path combine?

Path. Combine uses the Path. PathSeparator and it checks whether the first path already has a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.

What is the most efficient way to concatenate many strings together?

The most efficient is to use StringBuilder, like so: StringBuilder sb = new StringBuilder(); sb. Append("string1"); sb.


2 Answers

Path.Combine uses the Path.PathSeparator and it checks whether the first path already has a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.

like image 147
György Kőszeg Avatar answered Sep 17 '22 20:09

György Kőszeg


Path.Combine does more things than just a string concatenation. If you look at the source code;

  • Checks both paths has invalid character or not
  • Checks second parameter is root path or not
  • Checks last character of first path is director or alt directory or volume separator or not. If not, concatenate both string with directory separator between then
like image 39
Soner Gönül Avatar answered Sep 21 '22 20:09

Soner Gönül