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

C# 登錄表讀寫完整教學:Microsoft.Win32 實戰範例

     編輯:C# 入門

必要命名空間

using Microsoft.Win32;

讀取登錄值

public static string ReadReg(string keyName)
{
    string result = "";
    try
    {
        RegistryKey baseKey = Registry.LocalMachine; // 可依需求改 CurrentUser 等
        RegistryKey subKey = baseKey.OpenSubKey(@"SOFTWARE\Exobo");
        if (subKey != null)
        {
            result = subKey.GetValue(keyName)?.ToString() ?? "";
            subKey.Close();
        }
        baseKey.Close();
    }
    catch (Exception)
    {
        throw; // 實務建議記錄日誌後再決定是否拋出
    }
    return result;
}

建立/寫入登錄(首次註冊或更新)

public static bool CreateReg(string username, string password, string userType, string userMax, string userTime)
{
    try
    {
        RegistryKey baseKey = Registry.LocalMachine;
        RegistryKey subKey = baseKey.OpenSubKey(@"SOFTWARE\Exobo", true); // true = 可寫入

        if (subKey == null) // 不存在則建立
        {
            baseKey.CreateSubKey(@"SOFTWARE\Exobo");
            subKey = baseKey.OpenSubKey(@"SOFTWARE\Exobo", true);
        }

        subKey.SetValue(username, password);
        subKey.SetValue(username + "Type", userType);
        subKey.SetValue(username + "Time", userTime);
        subKey.SetValue(username + "Max", userMax);

        subKey.Close();
        baseKey.Close();
        return true;
    }
    catch (Exception)
    {
        throw;
    }
}

檢查登錄項目是否存在

public static bool HaveReg()
{
    try
    {
        RegistryKey baseKey = Registry.LocalMachine;
        RegistryKey subKey = baseKey.OpenSubKey(@"SOFTWARE\Exobo");
        bool exists = subKey != null;
        subKey?.Close();
        baseKey.Close();
        return exists;
    }
    catch (Exception)
    {
        throw;
    }
}

實務注意事項

  • 權限:寫入 LocalMachine 需系統管理員權限,建議改用 CurrentUser 避免 UAC 提示。
  • 路徑格式:使用 @\"SOFTWARE\Exobo\" 逐字字串避免跳脫字元錯誤。
  • 資源釋放:務必呼叫 Close() 或使用 using 區塊確保釋放。
  • 例外處理:生產環境請改為記錄日誌並回傳錯誤代碼,避免直接拋出。

掌握以上模式,即可在 C# 應用程式中安全、穩定地操作 Windows 登錄表。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved