Eminem
Eminem

Reputation: 7484

How should I handle windows/Linux paths in c#

My intention is for my application to run on windows and linux.
The application will be making use of a certain directory structure e.g.

appdir/  
      /images
      /sounds

What would be a good way of handling the differences in file(path) naming differences between windows and linux? I don't want to code variables for each platform. e.g. pseudo code

if #Win32
  string pathVar = ':c\somepath\somefile.ext';
else 
  string pathVar = '/somepath/somefile.ext';

Upvotes: 23

Views: 34609

Answers (3)

dsolimano
dsolimano

Reputation: 8986

How about using System.IO.Path.Combine to form your paths?

Windows example:

var root = @"C:\Users";
var folder = "myuser";
var file = "text.txt";
var fullFileName = System.IO.Path.Combine(root, folder, file);

//Result: "C:\Users\myuser\text.txt"

Linux example:

var root = @"Home/Documents";
var folder = "myuser";
var file = "text.txt";
var fullFileName = System.IO.Path.Combine(root, folder, file);

//Result: "Home/Documents/myuser/text.txt"

Upvotes: 8

SLaks
SLaks

Reputation: 887453

You can use the Path.DirectorySeparatorChar constant, which will be either \ or /.

Alternatively, create paths using Path.Combine, which will automatically insert the correct separator.

Upvotes: 43

user710046
user710046

Reputation:

If you're using Mono. In the System.IO.Path class you will find:

Path.AltDirectorySeparatorChar
Path.DirectorySeparatorChar

Hope this helps!

Upvotes: 0

Related Questions