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.
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.
You can see both the SDK versions and runtime versions with the command dotnet --info .
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With