简体   繁体   中英

Running command line in c#' processstartinfo

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();


}

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.

thanks my actual problem was vpncmd needed to be in C:\\Windows\\SysWOW64 although it was in c:\\windows\\system32 it didnt find it even by using a absolute path in the cmd. Your answer helped me to troubleshoot my isse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM