title: change tcp/ip port for sql server express using C#
body: <p>I am deploying SQL Server Express with my application and I need to have C# code that changes the TCP/IP properties without changing them in SQL Server Configuration Manager. </p>
  
  <p>The following code stops SQL Server then it changes the tcp port to 1433 and then starts SQL Server again. The code works fine on a Windows XP machine; however, it errors out on a Windows 7 machine. The error occurs on the <code>prot.Alter();</code> line.</p>
  
  <pre><code>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");
  }
  </code></pre>
  
  <p>The following error message is what I receive when I run it on a Windows 7 machine:</p>
  
  <blockquote>
    <p>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.<br>
    at System.Management.ManagementObject.MapOutParameters(Object[] args, ManagementBaseObject >outParams, IWbemClassObjectFreeThreaded outParamsClass)<br>
    at System.Management.ManagementObject.InvokeMethod(String methodName, Object[] args)<br>
    at Microsoft.SqlServer.Management.Smo.Wmi.WmiSmoObject.InvokeMgmtMethod(ManagementObject mo, >ManagementOperationObserver observer, String methodName, Object[] parameters)  </p>
    
    <p>--- End of inner exception stack trace ---<br>
    at Microsoft.SqlServer.Management.Smo.Wmi.WmiSmoObject.InvokeMgmtMethod(ManagementObject mo, >ManagementOperationObserver observer, String methodName, Object[] parameters)<br>
    at Microsoft.SqlServer.Management.Smo.Wmi.WmiSmoObject.AlterProtocolProperties
    (ProtocolPropertyCollection protocolProperties)<br>
    at Microsoft.SqlServer.Management.Smo.Wmi.ServerIPAddress.AlterImplWorker()<br>
    --- End of inner exception stack trace ---<br>
    at Microsoft.SqlServer.Management.Smo.Wmi.ServerIPAddress.AlterImplWorker()<br>
    at Microsoft.SqlServer.Management.Smo.Wmi.ServerProtocol.AlterImplWorker()<br>
    at Microsoft.SqlServer.Management.Smo.Wmi.ProtocolBase.Alter()<br>
    --- End of inner exception stack trace ---<br>
    at Microsoft.SqlServer.Management.Smo.Wmi.ProtocolBase.Alter()  </p>
  </blockquote>