简体   繁体   中英

Why is Path.Combine better than “\\”?

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.

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.

When you don't know the first directory (eg it comes from user input), you may have C:\\Directory or C:\\Directory\\ and Path.Combine will solve the trailing slash problem for you. It does have quirks with leading slashes for the next arguments though.

Second, while usually not a problem for most applications, with Path.Combine you aren't hard-coding the platform directory separator. For an application that can be deployed to other operating systems than windows this is convenient.

其他平台可以使用不同的Separator,例如/而不是\\所以不使用\\\\的原因是SO独立

In this case, it does not really matter, but why don't you just write:

string myFilePath = "C:\\myDoc.txt";

The Path.Combine() method is useful if you are working with path variables and you don't want to check for backslashes (or whatever slashing required, depending on the platform):

string myFilePath = Path.Combine(path, filename);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM