如何检查 Windows Registry 在 .NET Core 应用程序中是否可用?
How to check if Windows Registry is available in .NET Core application?
我的 .NET Core 库需要从注册表中读取一些信息(如果可用)或保留默认值(如果不可用)。我想知道这样做的最佳做法。
我想我可以将注册表 initialization/usage 块包装在 try/catch 中,或者我可以检查当前平台是否是 Windows 但我不认为这些是最佳实践(它是最好避免异常,并且不能保证任何基于 Windows 的平台都会有注册表等)。
现在,我会依靠
bool hasRegistry = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
但想知道是否有更多 reliable/universal 解决方案。
使用 RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
检查注册表就足够了。
如果某种 Windows 没有注册表(正如您在评论中指出的那样),它很可能会有新的 OSPlatform
属性 无论如何...
您可以使用微软的Windows Compatibility Pack读取注册表。检查他们的例子...
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");
}
我的 .NET Core 库需要从注册表中读取一些信息(如果可用)或保留默认值(如果不可用)。我想知道这样做的最佳做法。
我想我可以将注册表 initialization/usage 块包装在 try/catch 中,或者我可以检查当前平台是否是 Windows 但我不认为这些是最佳实践(它是最好避免异常,并且不能保证任何基于 Windows 的平台都会有注册表等)。
现在,我会依靠
bool hasRegistry = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
但想知道是否有更多 reliable/universal 解决方案。
使用 RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
检查注册表就足够了。
如果某种 Windows 没有注册表(正如您在评论中指出的那样),它很可能会有新的 OSPlatform
属性 无论如何...
您可以使用微软的Windows Compatibility Pack读取注册表。检查他们的例子...
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");
}