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


76

如何通过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);
}

Answers:


63

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

对于注册表值,您可以获取当前键的值的名称,并检查此数组是否包含所需的值名称。

例:

public static bool checkMachineType()
{    
    RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true);
    return (winLogonKey.GetValueNames().Contains("Start"));
}

17
后者的示例,因为这就是问题所在?
2014年

6
我不敢相信这是公认的答案
lewis4u

42
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;
}

28
@hsanders即使已经回答了问题,也总是欢迎添加有用的信息。堆栈溢出收到了来自Google的大量流量;)
DonkeyMaster 2013年

5
如果valueName不存在,则root.GetValue(valueName)!= null引发异常。
法鲁克

应该更改为返回root?.GetValue(valueName)!= null;
JMIII

如果valueName不存在,则GetValue会引发哪个异常?
BradleyGamiMarques

27
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
}

2
  RegistryKey rkSubKey = Registry.CurrentUser.OpenSubKey(" Your Registry Key Location", false);
        if (rkSubKey == null)
        {
           // It doesn't exist
        }
        else
        {
           // It exists and do something if you want to
         }

2
该解决方案是检查密钥是否存在。对于值,我们必须检查该键中的值列表
jammy 2014年

0
public bool ValueExists(RegistryKey Key, string Value)
{
   try
   {
       return Key.GetValue(Value) != null;
   }
   catch
   {
       return false;
   }
}

这个简单的函数仅在找到一个值但不为null时才返回true;否则,如果该值存在但为null或键中不存在该值,则返回false。


使用问题的方法:

if (ValueExists(winLogonKey, "Start")
{
    // The values exists
}
else
{
    // The values does not exists
}

0

当然,“ Fagner Antunes Dornelles”的答案是正确的。但是在我看来,还值得检查注册表分支本身,或者确保该部分完全存在。

例如(“肮脏的黑客”),我需要在RMS基础结构中建立信任,否则当我打开Word或Excel文档时,系统将提示我输入“ Active Directory权限管理服务”。这是我可以向企业基础结构中的服务器添加远程信任的方法。

foreach (var strServer in listServer)
{
    try
    {
        RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
        if (regCurrentUser == null)
            throw new ApplicationException("Not found registry SubKey ...");
        if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
            throw new ApplicationException("Not found value in SubKey ...");
    }
    catch (ApplicationException appEx)
    {
        Console.WriteLine(appEx);
        try
        {
            RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
            RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
            newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
        }
        catch(Exception ex)
        {
            Console.WriteLine($"{ex} Pipec kakoito ...");
        }
    }
}

-4
        internal static Func<string, string, bool> regKey = delegate (string KeyLocation, string Value)
        {
            // get registry key with Microsoft.Win32.Registrys
            RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object.
            if ((rk) == null) // if the RegistryKey is null which means it does not exist
            {
                // the key does not exist
                return false; // return false because it does not exist
            }
            // the registry key does exist
            return true; // return true because it does exist
        };

用法:

        // usage:
        /* Create Key - while (loading)
        {
            RegistryKey k;
            k = Registry.CurrentUser.CreateSubKey("stuff");
            k.SetValue("value", "value");
            Thread.Sleep(int.MaxValue);
        }; // no need to k.close because exiting control */


        if (regKey(@"HKEY_CURRENT_USER\stuff  ...  ", "value"))
        {
             // key exists
             return;
        }
        // key does not exist

from的返回类型GetValue永远不会是类型,RegistryKey那么为什么要强制转换呢?
NetMage
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.