tags:

views:

155

answers:

3

Is it possible to either use the System.IO.Path class, or some similar object to format a unix style path, providing similar functionality to the PATH class? For example, I can do:

Console.WriteLine(Path.Combine("c:\\", "windows"));

Which shows:

"C:\\windows"

But is I try a similar thing with forward slashes (/) it just reverses them for me.

Console.WriteLine(Path.Combine("/server", "mydir"));

Which shows:

"/server\\mydir"
+1  A: 

In this case i would use the class System.Uri or System.UriBuilder.

Side note: If you run your .NET code on a Linux-System with the Mono-Runtime, the Path class should return your expected behavior. The information that the Path class uses are provided by the underlying system.

Jehof
Thanks for that, but I can't find any methods in either of these classes that looks to be the equivelent of .Combine()?
pm_2
+1  A: 

You've got bigger problems, Unix accepts characters in a file name than Windows does not allow. This code will bomb with ArgumentException, "Illegal characters in path":

  string path = Path.Combine("/server", "accts|payable");

You can't reliably use Path.Combine() for Unix paths.

Hans Passant
+2  A: 

Path.Combine uses the values of Path.DirectorySeperatorChar and Path.VolumeSeparatorChar, and these are determined by the class libraries in the runtime - so if you write your code using only Path.Combine calls, Environment.SpecialFolder values, and so forth, it will run fine everywhere, since Mono (and presumably any .NET runtime) implements the native way of getting and building those paths for any platform it runs on. (Your second example, for instance, returns /server/mydir for me, but the first example gives c:\/windows )

If you want a UNIX-specific path hard-coded in all cases, Path.Combine isn't buying you anything: Console.WriteLine ("/server/mydir"); does what you want in the OP.

As Hans said though, different filesystems have different rules for allowed characters, path lengths, and etc., so the best practice, like with any cross-platform programming, is to restrict yourself to using the intersection of allowed features between the filesystems you're targeting. Watch case-sensitivity issues too.

Matt Enright