Programmatically Change TCP/IP Port for SQL Server Using C#

When automating the installation of SQL Server onto a computer, I generally want it to listen on Port 1433 instead of dynamic ports.

TcpIp

This can be accomplished in C#. Before writing the code, we need to add the following references to our Visual Studio project:

Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Management.Sdk.Sfc
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SqlWmiManagement
Microsoft.SqlServer.WmiEnum

Untitled-3

With these added, you can reference Microsoft.SqlServer.Management.Smo.Wmi, and implement the following code:

using Microsoft.SqlServer.Management.Smo.Wmi;

const string instanceName = "SQLEXPRESS";

var managedComputer = new ManagedComputer();

var service = managedComputer.Services[string.Concat("MSSQL$", instanceName)];

if (service.ServiceState == ServiceState.Running)
{
    service.Stop();
}

var serverInstance = managedComputer.ServerInstances[instanceName];

var serverProtocol = serverInstance.ServerProtocols["Tcp"];

var ipAddresses = serverProtocol.IPAddresses;

for (var i = 0; i < ipAddresses.Count; i++)
{
    var ipAddress = ipAddresses[i];

    if (!string.Equals(ipAddress.Name, "IPAll"))
    {
        continue;
    }

    ipAddress.IPAddressProperties["TcpPort"].Value = "1433";

    break;
}

serverProtocol.Alter();

service.Start();
Tagged on: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *