简体   繁体   English

在C#中访问Windows注册表

[英]Accessing windows registry in C#

I am trying to get all the SQL Instances installed on a local machine with the help of following code: 我正在尝试通过以下代码在本地计算机上安装所有SQL实例:

RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
string[] instances = (string[])rk.GetValue("InstalledInstances");

if (instances.Length > 0)    //Error
{
    foreach (string instance in instances)
    {
        MessageBox.Show(instance);
    }
}

It is giving the following exception: 它给出以下异常:

Object reference not set to an instance of an object. 你调用的对象是空的。

I've manually checked the 'Registry-Editor' and the specified keys exist, also there are two SQL Instances on my system. 我已经手动检查了“注册表编辑器”,并且指定的键存在,而且我的系统上还有两个SQL实例。

Now please tell me why it is not accessing the required key value? 现在,请告诉我为什么它没有访问所需的键值?

This line could be the issue string[] instances = (string[])rk.GetValue("InstalledInstances"); 该行可能是问题string [] instance =(string [])rk.GetValue(“ InstalledInstances”);

Because RegistryKey.GetValue Method (String) returns a object and you are casting that in to string[] 因为RegistryKey.GetValue方法(字符串)返回一个对象,并且您将其强制转换为字符串[]

before casting it to string[] you should check if the returned value is not null 在将其强制转换为string []之前,应检查返回的值是否不为null

I ran your code on my 64-bit machine. 我在64位计算机上运行了您的代码。 It worked fine. 工作正常。 Make sure you platform is set to AnyCPU or x64 but not x86 确保平台设置为AnyCPU或x64,但未设置为x86

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM