Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running command line in c#' processstartinfo

Tags:

c#

I am running the below from c#

vpncmd is in c:\windows\system32

running the vpncmd command string works fine when I run in the command prompt

If I replace vpncmd with a stock command like "ipconfig /all" it works fine

I have another system running exactly the same command that works fine (the only difference is this server is Windows Server 2016 and the one its working on is Server 2012)

result always comes back as ""

 ExecuteCommandBuild("vpncmd <server> /server /hub:<hub> /PASSWORD:<psswd> /cmd iptable");

 public void ExecuteCommandBuild(object command)
        {

            try
            {

                System.Diagnostics.ProcessStartInfo procStartInfo =
                new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command); 
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;               
                procStartInfo.CreateNoWindow = true;              
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();              
                string result = proc.StandardOutput.ReadToEnd();


}
like image 852
AShah Avatar asked Mar 31 '26 21:03

AShah


1 Answers

The reason for this is that you are actually creating a new process inside your process (cmd).

Instead, you need to call the process directly:

ExecuteCommandBuild("vpncmd", "<server> /server /hub:<hub> /PASSWORD:<psswd> /cmd iptable");


public void ExecuteCommandBuild(string fileName, string arguments)
        {

            try
            {

                System.Diagnostics.ProcessStartInfo procStartInfo =
                new System.Diagnostics.ProcessStartInfo(fileName, arguments); 
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;               
                procStartInfo.CreateNoWindow = true;              
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();              
                string result = proc.StandardOutput.ReadToEnd();


}

Also, ReadToEnd can create problems if the data is too big. If your data is large, I can provide the alternative asynchronous code if needed.

like image 141
Ctznkane525 Avatar answered Apr 02 '26 12:04

Ctznkane525



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!