简体   繁体   中英

How to get command prompt output

I'm writing ac# application for validating the detailed information about no.of lines changes in SVN commit. After providing the below arguments in command prompt, it displays the revision number, author name and last changed date etc...

Argument: svn info –r {revision no} {Source path}

Eg - svn info -r 113653 "F:\\SVN"

I have to achieve the same in C# also. While giving the above arguments in C#, it should read the output(revision number, author name and last changed date) from the command prompt and store it in a string. I have tried the StandardOutput.ReadToEnd() but couldn't meet my requirement. Any detailed explanation will be helpful.

Have you tried just running the command from a command prompt with C# as explained in this question ?

string strCmdText = @"/C svn info -r 113653 ""F:\SVN""";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);

You can use the following method to run a command and retrieve the standard output from the console :

    public static string StdOut(string args)
    {
        string cmdOut = "";

        ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/C " + args)
        {
            WindowStyle = ProcessWindowStyle.Hidden,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        };

        cmdOut = ExecuteCommand(cmdOut, startInfo);
        return cmdOut;
    }

It will return the output as a string. You will also need this method (as it is used in the above):

    private static string ExecuteCommand(string cmdOut, ProcessStartInfo startInfo)
    {
        Process p = Process.Start(startInfo);
        p.OutputDataReceived += (x, y) => cmdOut += y.Data;
        p.BeginOutputReadLine();
        p.BeginErrorReadLine();
        p.WaitForExit();

        return cmdOut;
    }

p.OutputdataReceived is a DataReceivedEventHandler and it will concatenate any std output received onto the cmdOut variable.

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