我正在尝试使用以下 C# 代码在列表框中显示可用的 SQL 服务器:
DataTable dt = SmoApplication.EnumAvailableSqlServers(false);
foreach (DataRow dr in dt.Rows)
{
listBox3.Items.Add(dr["Name"].ToString());
}
但是,列表框仍然是空的,当我调试时,我发现 dt.Rows
等于零,尽管我有一个装有 SQL Server 2012 Express 的服务器。
有什么想法吗?
最佳答案
一种可能是您没有 SQL Server Browser Service运行。根据 MSDN 页面:
SQL Server Browser contributes to the following actions:
- Browsing a list of available servers
- Connecting to the correct server instance
- Connecting to dedicated administrator connection (DAC) endpoints
我在 32 位应用程序请求本地 SQL 实例列表但由于机器上只有 64 位实例而出现空的情况下所做的另一件事是探查注册表:
List<string> servers = new List<string>();
// Get servers from the registry (if any)
RegistryKey key = RegistryKey.OpenBaseKey(
Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
key = key.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
object installedInstances = null;
if (key != null) { installedInstances = key.GetValue("InstalledInstances"); }
List<string> instances = null;
if (installedInstances != null) { instances = ((string[])installedInstances).ToList(); }
if (System.Environment.Is64BitOperatingSystem) {
/* The above registry check gets routed to the syswow portion of
* the registry because we're running in a 32-bit app. Need
* to get the 64-bit registry value(s) */
key = RegistryKey.OpenBaseKey(
Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
key = key.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
installedInstances = null;
if (key != null) { installedInstances = key.GetValue("InstalledInstances"); }
string[] moreInstances = null;
if (installedInstances != null) {
moreInstances = (string[])installedInstances;
if (instances == null) {
instances = moreInstances.ToList();
} else {
instances.AddRange(moreInstances);
}
}
}
foreach (string item in instances) {
string name = System.Environment.MachineName;
if (item != "MSSQLSERVER") { name += @"\" + item; }
if (!servers.Contains(name.ToUpper())) { servers.Add(name.ToUpper()); }
}
关于c# - smo.application.enumAvailableSqlServers 未返回可用的 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25001145/