Harry
Harry

Reputation: 29

How do I check the OS in the F# preprocessor?

We're multiple persons working on the same F# project. Some use MacOS and Visual Studio Code together with Ionide while others use Windows with Visual Studio. In the F#-code, we need to access some files, but MacOS uses / to specify paths while Windows uses \. In F#, how can we make something like:

#if OS_WINDOWS
    let path = "path\to\file.txt"
#elif OS_MAC
    let path = "path/to/file.txt"
#endif

Upvotes: 2

Views: 262

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243096

There is no built-in pre-defined symbol to indicate what operating system you are compiling for. When you use .NET, you generally use the same compiled assembly on all operating systems, so this is not something that you can reasonably do in a pre-processor anyway.

You can check what OS are you running on at runtime using System.Environment:

open System

let path = 
  if Environment.OSVersion.Platform = PlatformID.Win32NT then @"path\to\file.txt"
  else @"path/to/file.txt"

That said, if your only concern is slashes and backslashes in a path, you can just use:

let path = System.IO.Path.Combine("path", "to", "file.txt")

Upvotes: 4

Related Questions