我正在尝试使用C#将TcpPort更新为“1433”并将TcpDynamicPorts更新为“”,但我所做的任何更改都没有生效。我可以在C#中找到要更新的实例,然后确认实例中存在属性,但任何更新方法都会被忽略而不会出错。
try
{
var searcher = new ManagementObjectSearcher(@"\\.\root\Microsoft\SqlServer\ComputerManagement10",
"select * from ServerNetworkProtocolProperty where InstanceName='SQLEXPRESS' and ProtocolName='Tcp' and IPAddressName='IPAll'");
foreach (ManagementObject instance in searcher.Get())
{
PutOptions options = new PutOptions();
options.Type = PutType.UpdateOnly;
foreach (var property in instance.Properties)
{
if (property.Name == "PropertyName" && (string)property.Value == "TcpPort")
{
instance.SetPropertyValue("PropertyStrVal", "1433");
}
if (property.Name == "PropertyName" && (string)property.Value == "TcpDynamicPorts")
{
instance.SetPropertyValue("PropertyStrVal", "");
}
}
instance.Put(options);
}
}
catch (ManagementException e)
{
Console.WriteLine("An error occurred setting the WMI data: " + e.Message);
}
任何人都可以告诉我做错了什么吗?当我通过WMI Explorer 2.0查询属性时,一切都保持不变。
答案 0 :(得分:0)
正如我在评论中提到的那样,我认为写入注册表的方式更强大更快,并且比访问此任务的WMI更容易。所以你要做的就是
private static void registryChangeSqlServerPort()
{
/// SQL Server 2012 registry values
/// default instance
/// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQLServer\SuperSocketNetLib\TCP\IPAll
///
/// named instance
/// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL11.(InstanceName)\MSSQLServer\SuperSocketNetLib\TCP\IPAll
string instanceName = "SQLEXPRESS";
string key =
string.Format("SOFTWARE\\Microsoft\\Microsoft SQL Server\\MSSQL11.{0}\\MSSQLServer\\SuperSocketNetLib\\Tcp\\IPAll",
instanceName);
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(key, true);
/// change TcpPort settings
string valueName = "TcpPort";
string value = "1433";
regKey.SetValue(valueName, value, RegistryValueKind.String);
/// change TcpDynamicPort settings
valueName = "TcpDynamicPorts";
value = "";
regKey.SetValue(valueName, value, RegistryValueKind.String);
}
请参阅此SO-Question以获取sql server上的更多密钥。
请注意,在重新启动计算机之前,注册表中的任何更改都不会显示,因为它仅在启动时加载一次。即使在观看regedit.exe时使用F5刷新也无法显示更改的值!