views:

192

answers:

4

A question that's lurking in my head for a while now. What's the importance of Path.DirectorySeperatorChar ? I mean can't we just put '\' instead - which i think is faster than calling a property especially if you're constructing a huge number of paths in your application? Is there a reason for it? could there be another Char for folder/file path seperation other than '\' ? maybe in another operating system?

+15  A: 

Yes, use the property. It will be more future-proof. You will be compatible with Mono (Linux) but MS.NET may also move to other platforms (like Compact and Micro Framework).

But the best method is to use Path.Combine() and Path.GetFileName() et al, and then you won't be needing the separator char at all.

Henk Holterman
THanks a lot for the compatibility issues. Didn't know that
LolaRun
+1  A: 

On linux, separator is /. And we do have Mono there.

Josip Medved
+3  A: 

Use Path.Combine() for combining paths. Unfortunately, it's not as fast as it could be since the Path class' methods operate on string instead of a special struct (Path as a non-static class, perhaps?). Why is this a problem you ask? This gem:

Exceptions:
ArgumentException path1 or path2 contain one or more of the invalid characters defined in GetInvalidPathChars.

280Z28
No! no problem, i'm just asking for the performance optimization.But you said, 'it's not as fast as it could be'. The question is, is it theoretically faster than the normal string concatenation of the path.I mean, which is faster?Path.Combine() or directory1+Path.DirectorySeperatorChar+dir2.
LolaRun
`Path.Combine()` doesn't duplicate the separator if one is present at the end of `directory1` and/or the beginning of `directory2`. That said, manual implementation of the option would be significantly/measurably faster if you have to perform the operation thousands of times on the GUI thread. It probably wouldn't ever be a problem for background processes/tools, and certainly wouldn't for a "small number" of operations (hundreds or less).
280Z28
+1  A: 

Windows accepts / for path separators does it not? Just use that to be compatible. However, the combine method is better to use.

Josh Smeaton