一.安裝組件
對於 Windows 注冊表 的操作是不跨平台的,僅在 Windows 生效。
操作注冊表沒有包含在 BCL,是以 NUGET 包的方式提供,使用命令安裝:
dotnet add package Microsoft.Win32.Registry
二.檢查OS
因為操作注冊表的代碼只能在 Windows 才能正常運行,所以最好判斷一下系統
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Error("This application can only run on windows.");
Environment.Exit(-1);
}
三.管理員權限
注冊表根目錄有 5 項,其中操作 HKEY_CURRENT_USER 不需要管理員權限,但是操作其它就需要了
從 Nuget 安裝包 System.Security.Principal.Windows
使用以下代碼來判斷程序是否具有管理員權限:
using var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
var isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!isElevated)
{
Error("Administrator permission is required to running.");
Environment.Exit(-1);
}
四.注冊表操作
對注冊表的操作主要是用 Registry
類型,它包含了幾個屬性,分別對應上面提到的,注冊表根目錄的5項。
如 Registry.CurrentUser
對應 HKEY_CURRENT_USER
。
在寫代碼前要安利一下,注冊表對應在代碼中的術語:
打開注冊表指定 Key:
var key = Registry.CurrentUser.OpenSubKey("<Key>", true);
讀取 Key 下的值:
//先獲取ValueName
var keyNames = key.GetValueNames();
if (!keyNames.Any())
{
Success("No record found, no need to clear.");
return;
}
foreach (var name in keyNames)
{
//獲取值
key.GetValue(name);
//刪除值
key.DeleteValue(name);
}
獲取 Key 下的子Key:
var subKeyNames = key.GetSubKeyNames();
if (subKeyNames.Any())
{
foreach (var name in subKeyNames)
{
//刪除子Key
serverKey.DeleteSubKey(name);
}
}
添加或修改值:
key.SetValue("valuename","value");
添加子Key:
key.CreateSubKey("subkeyname");