如何读取注册表项 c # 的值

在我的应用程序启动时,我试图查看用户是否安装了特定版本的软件,特别是 MySQL 连接器,所有这些都使用 c # 。在注册表中,MySQL 包含一个版本条目。所以我要做的就是。

我的应用程序启动了。在启动代码的某个地方,我需要按顺序做以下事情。检查用户是否安装了 MySQL 连接器,该连接器位于..。

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MySQL AB\MySQL Connector/Net

如果用户已经安装了连接器,我想检查它们的版本,这个版本存储为 Name = “ Version”和 Data = x.x.x (如下图所示)

现在,如果用户已经安装了特定的版本,那么我将执行其他代码,这是我可以从中获取的。

最好的解决办法是什么?

enter image description here

编辑: 下面是我当前的代码,我在第19行得到一个错误(注释)。我的错误是“ error CS1001: Identifier Expected”,我不知道那是什么意思。有人帮忙吗?

using System;
using Microsoft.Win32;
using System.Data;


public class regTest
{
public static void Main()
{
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net");
if (key != null)
{
Object o = key.GetValue("Version");
if (o != null)
{
Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
Version broken = new Version("6.7.4");
if (version.Equals.(broken)) //This is where the error is occuring
{
DataSet dataSet = ConfigurationManager.GetSection("system.data") as ystem.Data.DataSet;


DataView vi = dataSet.Tables[0].DefaultView;
vi.Sort = "Name";
if (vi.Find("MySql") == -1)
{
dataSet.Tables[0].Rows.Add("MySql"
, "MySql.Data.MySqlClient"
, "MySql.Data.MySqlClient"
,
typeof(MySql.Data.MySqlClient.MySqlClientFactory).AssemblyQualifiedName);
}


}


}
}
}


catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
}
}
154429 次浏览

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
{
if (key != null)
{
Object o = key.GetValue("Version");
if (o != null)
{
Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
//do what you like with version
}
}
}
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

Change:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))

To:

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

@DonBoitnott have a good code, but require admin rights. I use this (only need Read Rights)

 try
{
using (var key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net", false)) // False is important!
{
var s = key?.GetValue("Version") as string;
if (!string.IsNullOrWhiteSpace(s))
{
var version = new Version(s);
}
}
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}