6

System.io.DirectorySeparatorChar returns the character "\" while System.io.AltDirectorySeparatorChar returns "/"

to be more specific what is the job of System.Io.AltDirectorySeparatorChar and when we use it?

Ahmed Ibrahim
  • 681
  • 8
  • 12
  • 2
    `to be more specific what is the job of System.Io.AltDirectorySeparatorChar and when we use it?` The job is to ensure that / works in paths all of the time, even for OSes (like Windows) that really prefer \. – mjwills Sep 25 '18 at 23:22
  • Does this answer your question? [Why are there two directory separator chars?](https://stackoverflow.com/questions/50905209/why-are-there-two-directory-separator-chars) – alelom Jul 29 '20 at 13:26

2 Answers2

3

From the documentation (https://learn.microsoft.com/en-us/dotnet/api/system.io.path.altdirectoryseparatorchar)

Provides a platform-specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organization.

You can use alt separator in your path strings the same way as you use normal separator. Like this:

static void Main(string[] args)
{
        string[] pathStrings =
        {
            @"C:\dir\subdir\file.txt",
            "C:/dir/subdir/file.txt",
            "/dir/subdir/file.txt"
        };

        foreach (var p in pathStrings)
        {
            var dir = Path.GetDirectoryName(p);
            var file = Path.GetFileName(p);
            Console.WriteLine($"{dir} {file}");
        }

}

And the output:

C:\dir\subdir file.txt
C:\dir\subdir file.txt
\dir\subdir file.txt
  • 4
    This does not answer the question at all. – alelom Jul 29 '20 at 13:14
  • This does not explain why we have DirectorySeparatorChar in addition to AltDirectorySeparatorChar. In fact, the only difference from their MSDN descriptions is that [the second uses the adjective "alternate"](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.altdirectoryseparatorchar?view=netcore-3.1), [while the first doesn't](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.directoryseparatorchar?view=netcore-3.1). – alelom Jul 29 '20 at 13:31
  • Windows supports both separators (which is obvious from the answer and is stated in the linked documentation), so I guess they needed two properties. –  Jul 30 '20 at 00:14
2

My understanding is that DirectorySeparatorChar is platform-specific default separator, while AltDirectorySeparatorChar is platform-independent universal separator.

On Windows : DirectorySeparatorChar is backslash, AltDirectorySeparatorChar is forward slash
On Unix-based : Both are forward slash

It is because Windows natively prefers backslash but also supports forward slash, while Unix-based systems only support forward slash. Practically, it means you can use either one.
I would personally prefer DirectorySeparatorChar, because I simply prefer backslash on Windows. But perhaps the best is to use Path.Combine and let the choice up to this method.