gpt4 book ai didi

c# - 使用 C# 更改 sql server express 的 tcp/ip 端口

转载 作者:可可西里 更新时间:2023-11-01 02:34:33 25 4
gpt4 key购买 nike

我正在使用我的应用程序部署 SQL Server Express,我需要 C# 代码来更改 TCP/IP 属性,而不需要在 SQL Server 配置管理器中更改它们。

以下代码停止 SQL Server,然后将 tcp 端口更改为 1433,然后再次启动 SQL Server。该代码在 Windows XP 机器上运行良好;但是,它在 Windows 7 机器上出错。错误发生在 prot.Alter(); 行。

try
{
Service Mysvc = mc.Services["MSSQL$SQL" + machineName];

if (Mysvc.ServiceState == ServiceState.Running)
{
MessageBox.Show("Stopping Service","PMP");
Mysvc.Stop();
}

ServerInstance s = mc.ServerInstances["SQL" + machineName];
ServerProtocol prot = s.ServerProtocols["Tcp"];
prot.IPAddresses[0].IPAddressProperties["TcpPort"].Value = "1433";
prot.Alter();

MessageBox.Show("Starting Service","PMP");
Mysvc.Start();
}
catch (Exception e)
{
MessageBox.Show("Error in setting TCP Port " + e.ToString(),"PMP");
}

以下错误消息是我在 Windows 7 机器上运行它时收到的消息:

SqlServer.Management.Smo.FailedOperationException: Alter failed. ---> Microsoft.SqlServer.Management.Smo.FailedOperationException: SetStringValue failed for ServerIPAddress 'IPAll'. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at System.Management.ManagementObject.MapOutParameters(Object[] args, ManagementBaseObject >outParams, IWbemClassObjectFreeThreaded outParamsClass)
at System.Management.ManagementObject.InvokeMethod(String methodName, Object[] args)
at Microsoft.SqlServer.Management.Smo.Wmi.WmiSmoObject.InvokeMgmtMethod(ManagementObject mo, >ManagementOperationObserver observer, String methodName, Object[] parameters)

--- End of inner exception stack trace ---
at Microsoft.SqlServer.Management.Smo.Wmi.WmiSmoObject.InvokeMgmtMethod(ManagementObject mo, >ManagementOperationObserver observer, String methodName, Object[] parameters)
at Microsoft.SqlServer.Management.Smo.Wmi.WmiSmoObject.AlterProtocolProperties (ProtocolPropertyCollection protocolProperties)
at Microsoft.SqlServer.Management.Smo.Wmi.ServerIPAddress.AlterImplWorker()
--- End of inner exception stack trace ---
at Microsoft.SqlServer.Management.Smo.Wmi.ServerIPAddress.AlterImplWorker()
at Microsoft.SqlServer.Management.Smo.Wmi.ServerProtocol.AlterImplWorker()
at Microsoft.SqlServer.Management.Smo.Wmi.ProtocolBase.Alter()
--- End of inner exception stack trace ---
at Microsoft.SqlServer.Management.Smo.Wmi.ProtocolBase.Alter()

最佳答案

UAC 是这里的问题。以管理员身份运行将解决问题。

关于c# - 使用 C# 更改 sql server express 的 tcp/ip 端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15930724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com