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

83

如何通过 C# 代码检查注册表值是否存在?这是我的代码,我想要检查“Start”是否存在。

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);
}
7个回答

72

对于注册表键,您可以在获取之后检查它是否为null。如果不存在,则会是null。

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

示例:

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

18
后面的内容翻译为:“这是后一种情况的例子,因为问题就是在问这个。” - cja
8
我无法相信这是被接受的答案 o.O - lewis4u

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

31
即使问题已经得到回答,添加有用的信息仍然受到欢迎。 Stack Overflow从谷歌获得了大量的流量;) - DonkeyMaster
5
如果valueName不存在,root.GetValue(valueName) != null会抛出异常。 - Farukh
应该改为 return root?.GetValue(valueName) != null; - JMIII
如果valueName不存在,GetValue会抛出哪个异常? - Bradley Marques

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

3
此解决方案是为了检查该键是否存在。对于值,我们需要检查该键中值的列表。 - jammy

1
当然,“Fagner Antunes Dornelles”的回答是正确的。但我认为除此之外,值得检查注册表本身,或确定确切存在的部分。
例如(“肮脏的黑客”),我需要建立对RMS基础设施的信任,否则当我打开Word或Excel文档时,将提示“Active Directory Rights Management Services”。以下是如何在企业基础设施中向我的服务器添加远程信任的方法。
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} - a terrible mistake ...");
        }
    }
}

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

这个简单的函数只有在找到一个非空值时才会返回true,否则如果存在值但它为空或者该键不存在,则返回false。

关于您的问题的使用方法:

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

-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

GetValue 的返回类型永远不会是 RegistryKey 类型,那你为什么要进行强制转换呢? - NetMage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接