Saturday, June 12, 2010

Platform Independent Path Descriptions

Yes, I have to admit, also I program not very cleanly. When describing paths I use the Backslash "\" out of comfort and readability reasons to separate folders. In C# though this has to be escaped by another Backslah or a prefixed "@", so I describe paths as follows:
string Pfad = @"C:\Dokumente und Einstellungen\Oliver";
But .Net is running also on other platforms (for Linux for example there exists the Mono - Project) and "\" does not work on all operating systems as a separator, the above path description could lead to an error there.
To guarantee platform independency the function Path.Combine() should better be used.
This combines the given strings to a path with valid separators.
So one could express above path as follows:
string Pfad = System.IO.Path.Combine("C:""Dokumente und Einstellungen""Oliver");
Pfad will then contain the following value on a Windows system:
"C:Dokumente und Einstellungen\\Oliver".
Alternatively one can also use directly Path.DirectorySeparatorChar to get the current separator character (System.IO has to be included via using).
string Pfad = "C:" + Path.DirectorySeparatorChar + "Dokumente und Einstellungen" + Path.DirectorySeparatorChar + "Oliver";
This also gives on Windows: "C:\\Dokumente und Einstellungen\\Oliver"

1 comment:

  1. I see that Path.DirectorySeperatorChar and path.combine shows \ on windows system. Can you confirm?