Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more: (untagged)
Hello,

I want to execute a command line command from my C#. I have written code that works but am not as expected. The code is taken from "How to Execute a Command in C# ?" found on this site. and is :
C#
public static int ExecuteCommand(string Command, int Timeout)
        {
            int ExitCode = -1;
            ProcessStartInfo ProcessInfo;
            Process Process;
            try
            {
                ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + Command);
                ProcessInfo.UseShellExecute = false;
                ProcessInfo.RedirectStandardOutput = true;
                //ProcessInfo.CreateNoWindow = false;
                //ProcessInfo.UseShellExecute = false;
                Process = Process.Start(ProcessInfo);
                
                // Get the results
                string result = Process.StandardOutput.ReadToEnd();
                Console.WriteLine("Process Result = " + result);
                Process.WaitForExit();
                ExitCode = Process.ExitCode;
                Console.WriteLine("%%%%%%%%%%% EXIT CODE = " + ExitCode);
                Process.Close();
            }
            catch (Exception e)  {
                Console.WriteLine("Error Processing ExecuteCommand : " + e.Message);
            }
            finally   {
                //Process = null;
                //ProcessInfo = null;
            }
            return ExitCode;
        }


The code runs, but untill I don't press "Ctrl+C" on dos prompt I don't see any results. I also want to check a line form the console text. For eg: If I find "Connected" from the output I want to close the process and return. Then when the user asks for disconnecting want to execute another command to disconnect the running application.

Why does the above code doesn't retun untill I press "Ctrl+c" on the command window (I don't want to show the command window also, right now am just showing)? Whne I press Ctrl+C I see the text on Console (output window), but want to check the text and on findling "Connected" want ot return and/or close the process.

Can anyone point out where am I going wrong and how to solve the problem and work out with it.

Any help is highly appreciated. Need to solve this early have already spend 2-3 days trying to solve the problem.

Thanks
Posted
Updated 31-Jan-11 22:21pm
v2

Hi,

I've just tested your function and have to admit that it is working perfectly when I call it with:
ExecuteCommand("dir", 1000);

Can you please tell us if a simple command as "dir" is working for you? Maybe the command you execute is faulty?!

Modified Answer:

You could use this code to see the output without waiting for the process to finish:
C#
public static int ExecuteCommand(string Command, int Timeout)
{
    int ExitCode = -1;
    ProcessStartInfo ProcessInfo;
    Process Process;
    try
    {
        ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + Command);
        ProcessInfo.UseShellExecute = false;
        ProcessInfo.RedirectStandardOutput = true;
        //ProcessInfo.CreateNoWindow = false;
        //ProcessInfo.UseShellExecute = false;
        Process = Process.Start(ProcessInfo);
        Process.BeginOutputReadLine();
        Process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
    }
    catch (Exception e)
    {
        Console.WriteLine("Error Processing ExecuteCommand : " + e.Message);
    }
    finally
    {
        //Process = null;
        //ProcessInfo = null;
    }
    return ExitCode;
}

static void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine(e.Data);
}
 
Share this answer
 
v3
Comments
JF2015 1-Feb-11 5:00am    
Thanks for your quick resposne.

Well, I am trying to connect to a server command. The same command if I run on command promt, its working.

But yes, from your statement, the command gets connected and the execution doesn't stop. Like eg:
c:/> connect args.txt
....
....
Connected


After displaying the text "connected" also the command is in running mode only. So I guess without closing it I should be able to retrieve the output text and on comaparing, should return if I find the appropriate text.

Then how to retrieve the text when the command is still in running mode?

Thanks
JF2015 1-Feb-11 5:05am    
It's hard to give you a proper solution without knowing what "connect" does. Is this an application you have written?
Maybe you could have a look at redirecting the output of the process as described here:
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx
JF2015 1-Feb-11 5:16am    
Please see my modified answer. Maybe this is what you need.
All Time Programming 1-Feb-11 5:37am    
I tried your latest code, but that also doesn't help. My command is :
openvpn --config client.ovpn --ca certificate.cer --auth-user-pass user.txt

Trying to connect to openvpn.
And when I find "Initialization Sequence Completed" I want to return to inform the user about connection successful. With your code also I don't see any text without pressing Ctrl+C. To stop openvpn, I got to press "F4" on command prompt. Till then the command prompt is active and in running mode. But I want to return my function once I have connected or receive any such error message from the openvpn.

From the link you provided, do you think "BeginOutputReadLine" could be of use as that's the only thing I have not implemented or tried in my code.

Thanks

JF2015 1-Feb-11 5:46am    
Modified the answer to use "BeginOutPutReadLine" - works for me but I don't have your executable to start.
This is because the process you start takes the console and holds it, because of WaitForExit. All correct. Your first line to see is "Process Result=", but by this moment the process is already started with "cmd /C". The process is not finished by whatever reason (depends on Command), and Timeout is not implemented.

—SA
 
Share this answer
 
Thanks SAKryukov,

According to your comment, I added time in WaitForExit(). Then after som much tme it should exit and return ! But it doesn't return, its still waiting only.

try
            {
                ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + Command);
                ProcessInfo.UseShellExecute = false;
                ProcessInfo.RedirectStandardOutput = true;
                //ProcessInfo.CreateNoWindow = false;
                Process = Process.Start(ProcessInfo);

                // Get the results
                string result = Process.StandardOutput.ReadToEnd();
                Console.WriteLine("Process Result = " + result);
                Process.WaitForExit(30000);

                //ExitCode = Process.ExitCode;
                //Console.WriteLine("%%%%%%%%%%% EXIT CODE = " + ExitCode);
                //Process.Close();
            }


As I said, the command doesn't stop untill I press F4 key. With the command, it gets connected to the server and text keeps on coming on the prompt. I want to read the text and as I find the text "Connected" want to return and inform the user that "the app is connected to the server".

I understand that Process.Exitcode also wont return and so is Process.close.

What changes are required for solving my issue. I believe their must be some way to run any such command that doesn't exit immediately but only after giving any Exit command like F4,etc.

Thanks
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 1-Feb-11 16:01pm    
Timeout is not what I mean (I only mentioned it is not implemented, to explain what you see). Some other idea is needed.

Could you please explain the the ultimate goals of all that activity?
You explain what is in Command, but why? So far, creating a process does not look like a healthy idea to me, so far...

Thank you.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900