iT邦幫忙

4

[C#] Registrykey 登錄機碼的新增、修改、刪除、讀取

原文:[C#] Registrykey 登錄機碼的新增、修改、刪除、讀取

寫 Windows 應用程式時,常常會將一些參數存至機碼裡面,今天來簡單的筆記一下 Registry 的 CRUD。

在 64-bits 的作業系統下執行 32-bits 或 64-bits 應用程式時,預設寫入 Registry 會被作業系統寫入 Wow6432Node 的目錄底下。在 HKEY_LOCAL_MACHINE\SOFTWARE\ 底下寫入機碼,就會出現在 HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\,其目的是為了區分 32-bits 與 64-bits 作業系統的對應而產生的結果,只有真正的 64-bits 應用程式才能寫在 HKEY_LOCAL_MACHINE\SOFTWARE\ 目錄。

新增、修改:

RegistryKey registryKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\RegistryKeyTest");
registryKey.SetValue("Path", "C:\\");

若新增對象不存在則會新增

讀取:

RegistryKey registryKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\RegistryKeyTest");
string value = registryKey.GetValue("Path")?.ToString();

刪除:

RegistryKey registryKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\RegistryKeyTest");
registryKey.DeleteValue("Path");

若刪除對象不存在則會拋 Exception.

刪除 Registry Key 及其底下所有內容:

Registry.LocalMachine.DeleteSubKeyTree(@"SOFTWARE\RegistryKeyTest");

若刪除對象不存在則會拋 Exception.

若要想自己指定寫入位置可以使用下面的方法來達成

var registry64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);

var registryKeyTest = registry64.CreateSubKey(@"SOFTWARE\RegistryKeyTest");
registryKeyTest.SetValue("Path", "C:\\aaa");

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言