|
 Sunday, July 29, 2007
« Ubuntu and Virtual PC 2007 Mouse Issues | Main | IIS 6 & PHP - Mimicking .htaccess Us... »

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.
#    Comments [2] |
Monday, July 30, 2007 2:47:38 PM (Eastern Standard Time, UTC-05:00)
Another trick is to use System.IO.Path.Combine(string path1, string path2). Of course, this doesn't work so well when you are assembling three parts of the path, like you're doing in your example.
Tuesday, July 31, 2007 4:16:36 PM (Eastern Standard Time, UTC-05:00)
Very true. You could also just do a Path.Combine(Path.Combine(path1, path2), path3) and I believe that would work to.

Heck, you could just do it in a look with an array/list of strings.

2.3 billion ways to skin this cat. :)
Name
E-mail
(will show your gravatar icon)
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview