Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Path.Combine better than "\\"?

Tags:

string

c#

Over the years, and again recently, I have heard discussion that everyone should use Path.Combine instead of joining strings together with "\\", for example:

string myFilePath = Path.Combine("c:", "myDoc.txt");  
// vs.  
string myFilePath = "C:" + "\\myDoc.txt";

I'm failing to see the benefit that the former version provides over the latter and I was hoping someone could explain.

like image 526
A.R. Avatar asked Nov 08 '13 13:11

A.R.


1 Answers

Building a path with Path.Combine is more readable and less error-prone. You don't need to think about directory separator chars(\\ or \ or / on unix, ...) or if the first part of the path does or does not end in \ and whether the second part of the path does or does not start with \.

You can concentrate on the important part, the directories and filenames. It's the same advantage that String.Format has over string concatenation.

like image 56
Tim Schmelter Avatar answered Sep 29 '22 07:09

Tim Schmelter