mthiffau
mthiffau

Reputation: 133

I'm writing C# code that has to run on windows and linux (under mono). Easy way to handle file paths on both?

I'm writing a mod for Kerbal Space Program that logs data to a text file for use in outside tools (matlab, etc). KSP works on both Linux and Windows and I would like my mod to play nice on both. I was kind of hoping that the mono implementation on linux would just do the smart thing and translate the \'s to /'s, especially since I'm just working with Directory.GetCurrentDirectory as my base, so I don't have to worry about detecting/specifying things like c:\ vs /.

An acceptable answer (at least for now) would be a decent way to determine which platform I'm running on and just generate the strings differently (use a seperator char variable that I can set instead of slash string literals). I could look that up myself though, I'm kind of hoping there's a slick solution. I tried Googling/searching on here but nothing really stood out.

Upvotes: 1

Views: 2179

Answers (3)

SushiHangover
SushiHangover

Reputation: 74164

Use the System.Path.* as much as you can. It will avoid you from having to do specific OS checks to determine temp dirs, app locations, data/Desktop/Doc locations...

And use Path.Combine and stay away from having to using path separators. If you are hand parsing and building paths using Path.PathSeparator, ask your why? The odds are there is a std framework method that does what you want. KISS ;-)

Upvotes: 0

James Ko
James Ko

Reputation: 34529

Use Path.PathSeparator. \ on Windows, / on Unix.

If you're looking to combine directory names, you can use Path.Combine.

To get the root directory (i.e. / or C:\, you can use Path.GetPathRoot(Directory.GetCurrentDirectory())).

More info in the Path docs.

Upvotes: 2

Mingye Wang
Mingye Wang

Reputation: 1374

Mono provides IOMap to convert pathnames, so you can use backslashes happily in your code and then use MONO_IOMAP=all mono something.exe to start your program. Mono has a page with suggestions on application portability.

Upvotes: 0

Related Questions