Windows 登錄儲存資料格式多樣,部分格式(如 REG_MULTI_SZ 多重字串、REG_BINARY 二進制值)無法直接以字串讀取,需特殊處理。
範例:讀取 Windows 安裝來源路徑。
string[] installSources = (string[])Registry.LocalMachine
.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Setup")
.GetValue("Installation Sources");
// 取得第一個路徑
string firstPath = installSources.GetValue(0).ToString();
範例:讀取 DirectX 版本資訊。
byte[] versionBytes = (byte[])Registry.LocalMachine
.OpenSubKey(@"SOFTWARE\Microsoft\DirectX")
.GetValue("InstalledVersion");
string directXVersion = "DirectX ";
for (int i = 0; i < versionBytes.Length; i++) {
if (versionBytes[i] != 0)
directXVersion += versionBytes[i].ToString();
}
// 也可讀取 Version 字串值輔助顯示
string versionStr = Registry.LocalMachine
.OpenSubKey(@"SOFTWARE\Microsoft\DirectX")
.GetValue("Version").ToString();
directXVersion += " (" + versionStr + ")";
REG_MULTI_SZ 需轉型為 string[] 陣列讀取。REG_BINARY 需轉型為 byte[],再逐位元組解析組合字串。Microsoft.Win32 命名空間。