Jammer
Jammer

Reputation: 10208

Alternative for LocalAppData environment variable on OSX

I'm just writing my first .Net Core application and am knocking into an issue on OSX.

I started writing this on PC and am just running some unit tests on OSX.

This line:

var localAppData = Environment.GetEnvironmentVariable("LocalAppData");

Returned the expected value on PC but returns null on OSX. What would be the tidiest way to make this cross-platform?

Are there any additional considerations when applications are distributed in PKGs in terms of runtimes etc?

Many of the answers I'm finding in realtion to this talk about adding things to the launchd.conf which is all well and good for my development environment but what about when this is being run on a users machine?

What I'm trying is to find a way to retrieve some OSX equivalent of the Windows AppData.

A location where users applications can safely create files and store data that preconfigured on every OSX system.

Upvotes: 1

Views: 3087

Answers (1)

Chris HG
Chris HG

Reputation: 1492

Here's what I'm using:

string GetLocalAppDataFolder() {
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
    {
        return Environment.GetEnvironmentVariable("LOCALAPPDATA");
    }
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
    {
        return Environment.GetEnvironmentVariable("XDG_DATA_HOME") ?? Path.Combine(Environment.GetEnvironmentVariable("HOME"),".local","share");
    } 
    if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
    {
        return Path.Combine(Environment.GetEnvironmentVariable("HOME"), "Library", "Application Support");
    }
    throw new NotImplementedException("Unknown OS Platform");
}

The logic is as follows:

  • On Windows it returns the LOCALAPPDATA enviornment variable (usually something like C:\Users\{username}\AppData\Local).
  • On Linux it returns the XDG_DATA_HOME enviornment variable, or if that's not available the HOME variable appended with /.local/share (as per the FreeDesktop Base Directory Specification)
  • On MacOS it returns the HOME variable, appended with the path /Library/Application Support (so by default you'll end up with /Users/{username}/Library/Application Support

Upvotes: 1

Related Questions