Not a subscriber?

Join thousands of others who are building self-directed lives through creativity, grit, and digital strategy—breaking free from the 9–5.
Receive one free message a week

Tip: DirectorySeparatorChar

If you look at most file access code you’ll see the following somewhere:

string filePath = myDirectory + "\\" + myOtherDirectory + "\\" + myfile;

Developers will build their file paths with hard coded values such as “\\”. This isn’t the best way to accomplish things. For example, what happens if your code needs to get run on Mono? *NIX paths are different than that of Windows. When I see a string literal with a directory separator in it, or even in a constant, I cringe. How do we get around this? Easy…

Enter DirectorySeparatorChar

In the .NET Framework, in the System.IO Namespace in the Path class you’ll find a public static field by the name of DirectorySeparatorChar.

Here’s what it does: In a Windows and Mac environment it will return the backslash character. In a *NIX environment it will return a slash “/”.

No more hard coding separator characters!

You would now build the same path above, like this:

string filePath = myDirectory + Path.DirectorySeparatorChar + myOtherDirectory + 
                 Path.DirectorySeparatorChar + myfile;
The code is now much more stable and is much easier to adapt to a *NIX type of environment.