So as I am building a Folder/File checking conditional, and a co-worker says it is "better" to use Path.Combine:
string finalPath = Path.Combine(folder, "file.txt");
as opposed to the way I was doing it with
string finalPath = folder + "\\file.txt";
Any sound reasoning this is "better?"
It's an interesting question;
You could, of course, write something like:
To achieve the result you want.
Using ILSpy, though, lets see why Path.Combine is better.
The overload you are calling is:
The advantages are obvious; firstly, the function checks for null values and throws the appropriate exception. Then it checks for illegal characters in either of the arguments, and throws an appropriate exception. Once it is satisfied, it calls Path.CombineNoChecks:
The most interesting thing here are the characters it supports;
So it will also support paths where the separator is the wrong way around (like from a urn
file://C:/blah
, too)In short, it's better because it gives you validation, a degree of portability (the 3 constants shown above can be defined on a per framework-OS basis), and has support for more than one type of path that you commonly encounter.
One really could thing plus the other comments, it is the capability to combine many parts of the directory you want to create.
As an example is this:
It supports many characters as it receives an array of string, so it is capable to create the right directory in one single executed line.
Regards,
try these two to see the difference.... It can handle URI and standard paths. So always use
Path.Combine
.Output
file:///c:/temp/x.xml
Output
C:\test\x.xml
First you can use this notation
@"\file.txt
instead of"\\file.txt";
Second, let .Net care about fixing the path. There is a reason we have it. You can be 100% sure that you've done it correctly but if you start combining paths by hand everywhere in your code, there is always a chance to create bugs.
A simple example.
temp
there. What will you do?If no backslash at the end, add one, else do this, otherwise do the other... etc. With
Path.Combine()
you don't have to do checking. You can concentrate on the actual logic of your application.Yes, it's more portable in the case that the file-path separator is different to
\