.NET Framework => Core: Getting The App Data Folder

This is the first in my series of blog posts that will describe major changes to coding if you are trying to convert from the .NET Framework to .NET Core.

First up, getting the folder the app should use to save data. In the .NET Framework it was really easy by doing the following:

public string AppDataFolder()
{
  var path = System.IO.Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.LocalApplicationData), 
    My.Application.Info.CompanyName.Trim);
  return path;
}

Unfortunately, not so easy or “built-in” in .NET Core. Here is the work around:

public static string AppDataFolder()
{
  var userPath = Environment.GetEnvironmentVariable(
    RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 
    "LOCALAPPDATA" : "Home");

  var assy = System.Reflection.Assembly.GetEntryAssembly();
  var companyName = assy.GetCustomAttributes<AssemblyCompanyAttribute>()
    .FirstOrDefault();
  var path = System.IO.Path.Combine(userPath, companyName.Company);

  return path;
}

Besides a lot more work just to get the data folder, I’d like to point out something new, the RuntimeInformation.IsOSPlatform method. Since Core supports multiple non-Windows OS’s, this is an important method to remember going forward.


More code like this can be found in my open-source project on GitHub: http://bit.ly/DNTUtility