17

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';
Eminem
  • 7,206
  • 15
  • 53
  • 95

3 Answers3

35

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.

Ankush Jain
  • 5,654
  • 4
  • 32
  • 57
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 5
    Do you mean [`Path.DirectorySeparatorChar`](https://msdn.microsoft.com/en-us/library/system.io.path.directoryseparatorchar%28v=vs.110%29.aspx)? – Wai Ha Lee Jan 04 '16 at 15:10
  • Would anyone mind commenting on https://stackoverflow.com/questions/68723456/windows-vs-unix-path-on-transfer-data-in-net as well? I've seem to have stumbled on a bit of a "loophole". – JasonX Aug 16 '21 at 07:20
  • so all my path constants would look like: `var tempPath = $"{Path.Directory.SeparatorChar}Appname{Path.Directory.SeparatorChar}Folder1{Path.Directory.SeparatorChar}temp1{Path.Directory.SeparatorChar}A";` very nice and clear :) – user5629690 Jul 26 '23 at 07:54
8

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"
Imran Sh
  • 1,623
  • 4
  • 27
  • 50
dsolimano
  • 8,870
  • 3
  • 48
  • 63
  • 3
    What if you need to work with linux paths while running the code on windows? – Yarek T Mar 04 '21 at 10:31
  • @YarekT Path.Combine is intended to be a cross platform path combiner. I haven't tried it on Linux but it is supposed to work. – dsolimano Mar 09 '21 at 13:43
  • 1
    calling Path.Combine on windows creates windows paths. My project runs on and interacts with other linux machines, but some of our developers work on windows, so this creates inconsistencies. – Yarek T Mar 27 '21 at 08:28
0

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

Path.AltDirectorySeparatorChar
Path.DirectorySeparatorChar

Hope this helps!