Should I use Path.DirectorySeperatorChar C #

The question that lurks in my head for a while. What is 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 create a huge number of paths in your application? Is there a reason for this? can there be another Char to split a folder / file other than '\'? perhaps in a different operating system?

+4
source share
5 answers

Yes, use the property. It will be more promising. You will be compatible with Mono (Linux), but MS.NET can also switch to other platforms (for example, Compact and Micro Framework).

But the best way is to use Path.Combine() and Path.GetFileName() et al, and you won’t need a char delimiter at all.

+15
source

Use Path.Combine() to combine paths. Unfortunately, this is not as fast as it could be, since the methods of the Path class work on string instead of a special structure ( Path as a non-static class, maybe?). Why is this problem you ask? This stone:

Exceptions:
ArgumentException path1 or path2 contains one or more invalid characters defined in GetInvalidPathChars .

+3
source

On linux, the delimiter is /. And we have Mono.

+1
source

Windows accepts / for path separators, right? Just use this to be compatible. However, it is better to use the combination method.

+1
source

Make code compatible with other platforms, such as Unix, which uses slashes to separate paths. I believe that in Windows itself there are some special corner cases, for example, with device drivers.

Clarification of Josh's answer: Windows usually takes a slash for path separators, but not every Windows application, and there may be some places that Windows doesn't have either. For example, on the command line, a slash typically enters a parameter. Therefore, I would not personally rely on this.

I agree that in some situations there is quite a lot of something that you want to use. In my own (Delphi) code, I used the "AddSlash" method, which added, if necessary, a slash of the desired type. You can imagine a new language character or a character constant that is decoded to the right char for the platform.

0
source

All Articles