如何使用C#检查注册表值是否存在?

sar*_*i k 72 c# registry

如何检查C#代码是否存在注册表值?这是我的代码,我想检查"开始"是否存在.

public static bool checkMachineType()
{
    RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true);
    string currentKey= winLogonKey.GetValue("Start").ToString();

    if (currentKey == "0")
        return (false);
    return (true);
}
Run Code Online (Sandbox Code Playgroud)

260*_*986 60

对于注册表项,您可以在获取后检查它是否为空.如果它不存在,它将是.

对于Registry Value,您可以获取当前键的Values名称,并检查此数组是否包含所需的Value名称.

  • 后者的例子,因为那是问题所在? (17认同)
  • 我无法相信这是公认的答案oO (4认同)

Mik*_*uno 41

public static bool RegistryValueExists(string hive_HKLM_or_HKCU, string registryRoot, string valueName)
{
    RegistryKey root;
    switch (hive_HKLM_or_HKCU.ToUpper())
    {
        case "HKLM":
            root = Registry.LocalMachine.OpenSubKey(registryRoot, false);
            break;
        case "HKCU":
            root = Registry.CurrentUser.OpenSubKey(registryRoot, false);
            break;
        default:
            throw new System.InvalidOperationException("parameter registryRoot must be either \"HKLM\" or \"HKCU\"");
    }

    return root.GetValue(valueName) != null;
}
Run Code Online (Sandbox Code Playgroud)

  • @hsanders即使问题已经回答,也欢迎添加有用的信息.堆栈溢出会从Google获得大量流量;) (28认同)
  • root.GetValue(valueName)!= null如果valueName不存在则抛出异常. (4认同)

Jav*_*ram 24

string keyName=@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\services\pcmcia";
string valueName="Start";
if (Registry.GetValue(keyName, valueName, null) == null)
{
     //code if key Not Exist
}
else
{
     //code if key Exist
}
Run Code Online (Sandbox Code Playgroud)