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 登錄表。