System.IO.Path or equivalent use with Unix paths

Is it possible to 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 I'm trying to use a similar thing with a slash (/), it just changes them for me.

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

Which shows:

 "/server\\mydir" 
+6
c # unix path
source share
3 answers

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

Note: if you run your .NET code on a Linux system with Mono-Runtime, the Path class should return your expected behavior. The information that the Path class uses is provided by the base system.

+3
source share

You have big problems, Unix accepts characters in a file name, than Windows does not allow. This code will bomb using ArgumentException, "Illegal Characters in the Way":

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

You cannot reliably use Path.Combine () for Unix paths.

+3
source share

Path.Combine uses the values โ€‹โ€‹of Path.DirectorySeperatorChar and Path.VolumeSeparatorChar , and they are defined by class libraries at runtime, so if you write your code using only Path.Combine tags, Environment.SpecialFolder values, etc. go ahead, it will work fine everywhere, since Mono (and, presumably, any .NET runtime) implements its own way of getting and building these paths for any platform on which it works. (For example, your second example returns /server/mydir for me, but the first example gives c:\/windows )

If you want UNIX hard code to be defined in all cases, Path.Combine does not buy anything: Console.WriteLine ("/server/mydir"); does what you want in the OP.

As Hans said, different file systems have different rules for allowed characters, path lengths, etc., so the best practice, as with any cross-platform programming, is to limit yourself to using the intersection of allowed functions between file systems, which you are targeting. See also case sensitivity issues.

+3
source share

All Articles