首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 讀取 Windows 登錄多重字串與二進制值

     編輯:關於C#

前言

Windows 登錄儲存資料格式多樣,部分格式(如 REG_MULTI_SZ 多重字串、REG_BINARY 二進制值)無法直接以字串讀取,需特殊處理。

讀取 REG_MULTI_SZ(多重字串)

範例:讀取 Windows 安裝來源路徑。

string[] installSources = (string[])Registry.LocalMachine
    .OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Setup")
    .GetValue("Installation Sources");
// 取得第一個路徑
string firstPath = installSources.GetValue(0).ToString();

讀取 REG_BINARY(二進制值)

範例:讀取 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 命名空間。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved