c# - smo.application.enumAvailableSqlServers 未返回可用的 SQL Server

标签 c# sql smo

我正在尝试使用以下 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/

相关文章:

mysql - 如何根据另一个表中的 %LIKE% 值过滤一个表

azure - 当并非所有数据库都有用于连接到服务器的用户时,如何使用 SMO 列出 SQL Azure 服务器上的数据库?

c# - 无法加载文件或程序集 'Microsoft.SqlServer.BatchParserClient.dll 文件名

sql - 将具有多列的单行转置为两列的多行

c# - Cosmos DB - Mongo API - 文档不包含分片键

c# - 使用c#导入json数据

c# - 删除特定控件的所有事件处理程序

php - 检查用户名是否存在sql和php中的代码

powershell - 为什么 powershell 不保留 native 类型?

C# KeyDown事件多个Key加ControlKey