Search code examples
c#netsh

Netsh.exe run line


Consider:

 System.Diagnostics.ProcessStartInfo netshprocess = new System.Diagnostics.ProcessStartInfo();
 netshprocess.FileName = "netsh.exe";
 string temp = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
 string user = "";
 for (int i = 0; i < temp.Length; i++)
 {
     user += temp[i];
     if (temp[i] == '\\')
     {
         user = "";
     }
  }
  netshprocess.Arguments = "";
  netshprocess.Arguments = "http add urlacl url=http://+:7015/MeasurementTransferWCF user=" + user;
  netshprocess.UseShellExecute = true;
  System.Diagnostics.Process.Start(netshprocess).WaitForExit();

I cannot seem to get it to run it through the code. When I open netsh.exe and manually type in the exact string that the code has for the argument, it works (tested and then deleted the add so I can can try and do it in code). I have tried in running as administrator mode as well, but it doesn't work. What am I missing to get it to run?

It doesn’t error. It just doesn't run the argument when process.start is called.


Solution

  • Use:

     System.Diagnostics.ProcessStartInfo netshprocess = new System.Diagnostics.ProcessStartInfo();
     netshprocess.FileName = "netsh.exe";
    
     string temp = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
     string user = "";
    
     for (int i = 0; i < temp.Length; i++)
     {
         user += temp[i];
         if (temp[i] == '\\')
         {
             user = "";
         }
     }
    
     netshprocess.Verb = "runas";
     netshprocess.Arguments = "";
     netshprocess.Arguments = "http add urlacl url=http://+:7015/MeasurementTransferWCF user=" + user;
     netshprocess.UseShellExecute = true;
    
     try
     {
         System.Diagnostics.Process.Start(netshprocess).WaitForExit();
     }
     catch (Exception)
     { }
    

    With the verb run as when the user clicks "yes", it will be added. But if they click "no", you now need to catch the exception as it will git failed to run error.