C# 注册表值更改错误(对象引用未设置为对象的实例)

C# 注册表值更改错误(对象引用未设置为对象的实例),c#,compiler-errors,registry,C#,Compiler Errors,Registry,我目前正在尝试制作一个小程序,将我的标准音频设备从USB耳机改为扬声器。在使用Regshot查找通过手动切换音频设备而更改的注册表项后,我能够找到扬声器和耳机的二进制代码 static void Main(string[] args) { RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices

我目前正在尝试制作一个小程序,将我的标准音频设备从USB耳机改为扬声器。在使用Regshot查找通过手动切换音频设备而更改的注册表项后,我能够找到扬声器和耳机的二进制代码

static void Main(string[] args)
    {
        RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render\\{02b3c792-0c05-486c-be02-2ded778dc236}", true);
        standarddevice.SetValue("Role:0", "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
        standarddevice.SetValue("Role:1", "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
        standarddevice.SetValue("Role:2", "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    }

我无法解决的问题是,我得到了一个“对象引用未设置为对象实例”错误。

您的standarddevice对象似乎为空


很可能是因为指定的密钥不存在

查看文档:

  • 如果
    Open
    操作失败,
    OpenSubKey
    将返回
    null
要解决此问题,您应该检查null并执行适当的操作,可能是:

RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey(
    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render\\" + 
    "{02b3c792-0c05-486c-be02-2ded778dc236}", true);

if (standardDevice != null)
{
    standarddevice.SetValue("Role:0", 
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    standarddevice.SetValue("Role:1", 
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    standarddevice.SetValue("Role:2", 
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
}
如果您看到密钥确实存在,那么如果您在64位机器上,它可能位于WOW6432节点下。在这种情况下,您可以尝试以下方法:

RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey(
    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render\\" + 
    "{02b3c792-0c05-486c-be02-2ded778dc236}", true);

if (standardDevice == null)  
{
    standarddevice = Registry.LocalMachine.OpenSubKey(
       "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\" +
       "Audio\\Render\\{02b3c792-0c05-486c-be02-2ded778dc236}", true);
}

if (standardDevice != null)
{
    standarddevice.SetValue("Role:0", 
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    standarddevice.SetValue("Role:1", 
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
    standarddevice.SetValue("Role:2", 
        "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
}
可能重复的