Ale*_*lex 6 c# registry .net-core
我的.NET Core库需要从注册表中读取一些信息(如果可用),或者保留默认值(如果没有)。我想知道这样做的最佳做法。
我认为我可以将注册表初始化/使用代码块包装在try / catch中,也可以检查当前平台是否为Windows,但我不认为这些是最佳做法(最好避免出现异常,并且不能保证任何Windows-基于平台的将具有注册表等)。
现在,我将依靠
bool hasRegistry = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
Run Code Online (Sandbox Code Playgroud)
但想知道是否有更可靠/通用的解决方案。
检查注册表RuntimeInformation.IsOSPlatform(OSPlatform.Windows)就足够了。
如果某种 Windows 没有注册表(如您在评论中所指出的),它很可能OSPlatform无论如何都会有新的属性......
您可以使用 Microsoft 的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");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2961 次 |
| 最近记录: |