You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过C#解决SQL Server Express 2019 TCP协议启用的实例获取问题

解决SQL Server Express 2019 TCP协议启用时ServerInstances为空的问题

一、C#直接使用Smo.Wmi的解决步骤

  • 确认实例名称:SQL Server Express默认实例名为SQLEXPRESS,可通过服务列表验证(服务名格式为MSSQL$SQLEXPRESS)。若为自定义命名实例,需对应替换。
  • 安装匹配的SMO包:放弃GAC引用,通过NuGet安装Microsoft.SqlServer.SqlManagementObjects和Microsoft.SqlServer.Management.Smo.Wmi,版本选择15.x(适配SQL Server 2019)。
  • 指定WMI命名空间:Windows 11下需显式指定SQL 2019对应的WMI命名空间,避免默认路径匹配错误:
    var mc = new ManagedComputer(@"\\localhost", null, null, "root\\Microsoft\\SqlServer\\ComputerManagement15");
    mc.Refresh(); // 强制刷新WMI缓存
    var instance = mc.ServerInstances["SQLEXPRESS"];
    
  • 修复位数兼容性:若C#程序为32位,而SQL Server是64位,会导致WMI访问失败。将项目目标平台改为AnyCPU或x64。

二、C#调用PowerShell脚本的问题解决

  • 强制调用64位PowerShell:默认C#调用的可能是32位PowerShell(SysWOW64路径),需指定64位路径:C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe。
  • 脚本中显式指定WMI命名空间:避免脚本默认路径错误,修改脚本如下:
    $wmi = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer "localhost", $null, $null, "root\Microsoft\SqlServer\ComputerManagement15"
    $instance = $wmi.ServerInstances["SQLEXPRESS"]
    $tcpProtocol = $instance.ServerProtocols["Tcp"]
    $tcpProtocol.IsEnabled = $true
    $tcpProtocol.Alter()
    # 重启SQL服务使设置生效
    Restart-Service "MSSQL`$SQLEXPRESS" -Force
    
  • 确保权限传递:C#调用时需保证以管理员权限运行,配置ProcessStartInfo:
    var psi = new ProcessStartInfo(
        @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
        "-ExecutionPolicy Bypass -File \"C:\\EnableSqlTcp.ps1\""
    )
    {
        UseShellExecute = true,
        Verb = "runas",
        CreateNoWindow = false // 保留窗口便于查看错误输出
    };
    Process.Start(psi).WaitForExit();
    

三、通用排查点

  • 验证SQL Server配置管理器是否能识别实例:若配置管理器也看不到实例,需重新安装SQL Server管理工具组件。
  • 用WMIC命令测试WMI连通性:执行wmic /namespace:\\root\Microsoft\SqlServer\ComputerManagement15 path ServerInstance get Name,若无法返回实例名,修复WMI或SQL Server的WMI提供程序。
  • 检查WMI权限:在WMI控制台中,右键root\Microsoft\SqlServer\ComputerManagement15,为当前用户分配允许级别的WMI访问权限。

内容的提问来源于stack exchange,提问作者anoop choudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 23:12:41