Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should we use Path.DirectorySeperatorChar C#

Tags:

string

c#

.net

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?

like image 800
LolaRun Avatar asked Nov 30 '22 12:11

LolaRun


2 Answers

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.

like image 146
Henk Holterman Avatar answered Dec 12 '22 17:12

Henk Holterman


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.

like image 34
Sam Harwell Avatar answered Dec 12 '22 17:12

Sam Harwell