Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Windows Registry is available in .NET Core application?

My .NET Core library needs to read some info from registry if it's available or leave the default value if it's not. I would like to get the idea of best practices of doing that.

I think I could wrap the registry initialization/usage block in try/catch or I can check if the current platform is Windows but I don't think these are best practices (it's better to avoid exceptions and there is no guarantee that ANY Windows-based platform will have the registry, etc).

For now, I will rely on

bool hasRegistry = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

but wondering if there is a more reliable/universal solution.

like image 824
Alex Avatar asked Dec 08 '16 16:12

Alex


People also ask

How do I find Windows Registry?

There are two ways to open Registry Editor in Windows 10: In the search box on the taskbar, type regedit, then select Registry Editor (Desktop app) from the results. Right-click Start , then select Run. Type regedit in the Open: box, and then select OK.

How do I check my current .NET core version?

You can see both the SDK versions and runtime versions with the command dotnet --info .

What is registry in C#?

The Windows Registry is a hierarchical database that comprises of a collection of Keys, Sub Keys, Predefined Keys, Hives, and Value Entries and can be used to store system specific or application specific data.


1 Answers

Checking for registry with RuntimeInformation.IsOSPlatform(OSPlatform.Windows) is sufficient.

If some kind of Windows will not have registry (as you noted in comments), it will most probably have new OSPlatform property anyway...

You can use Microsoft's Windows Compatibility Pack for reading registry. Check their example...

private static string GetLoggingPath()
{
    // Verify the code is running on Windows.
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
    {
        using (var key = Registry.CurrentUser.OpenSubKey(@"Software\Fabrikam\AssetManagement"))
        {
            if (key?.GetValue("LoggingDirectoryPath") is string configuredPath)
                return configuredPath;
        }
    }

    // This is either not running on Windows or no logging path was configured,
    // so just use the path for non-roaming user-specific data files.
    var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
    return Path.Combine(appDataPath, "Fabrikam", "AssetManagement", "Logging");
}
like image 153
Matěj Pokorný Avatar answered Oct 03 '22 09:10

Matěj Pokorný