我使用下面的代码获取本地计算机中的所有实例名称和服务器名称。
private List<string> GetInstanceName()
{
var result = new List<String>();
RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
if (instanceKey != null)
{
foreach (var instanceName in instanceKey.GetValueNames())
{
if (!string.IsNullOrEmpty(instanceName))
{
result.Add(instanceName);
}
}
}
}
return result;
}
但我也需要获得版本。我不知道如何为每个实例获取版本。
答案 0 :(得分:2)
使用“Instance Names \ SQL”中的注册表项值获取的信息,您需要再次返回注册表并获取您正在查找的信息。
试试这段代码:
// find the installed SQL Server instance names
RegistryKey key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL");
// loop over those instances
foreach (string sqlInstance in key.GetValueNames())
{
Console.WriteLine("SQL Server instance: {0}", sqlInstance);
// find the SQL Server internal name for the instance
string internalName = key.GetValue(sqlInstance).ToString();
Console.WriteLine("\tInternal instance name: {0}", internalName);
// using that internal name - find the "Setup" node in the registry
string instanceSetupNode = string.Format(@"SOFTWARE\Microsoft\Microsoft SQL Server\{0}\Setup", internalName);
RegistryKey setupKey = baseKey.OpenSubKey(instanceSetupNode, false);
if (setupKey != null)
{
// in the "Setup" node, you have several interesting items, like
// * edition and version of that instance
// * base path for the instance itself, and for the data for that instance
string edition = setupKey.GetValue("Edition").ToString();
string pathToInstance = setupKey.GetValue("SQLBinRoot").ToString();
string version = setupKey.GetValue("Version").ToString();
Console.WriteLine("\tEdition : {0}", edition);
Console.WriteLine("\tVersion : {0}", version);
Console.WriteLine("\tPath to instance: {0}", pathToInstance);
}
}
答案 1 :(得分:0)
最可靠的答案是使用
.ustatus