GJ.
GJ.

Reputation: 111

Cannot get the output of command line in c#

I want to get the output of an execution in c# and I referred to this question. But I only have the output be printed on the console but not stored in the specified string. Here is my code: `

        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        //p.StartInfo.CreateNoWindow = true;

        p.StartInfo.FileName = "ffmpeg.exe";
        p.StartInfo.Arguments = " -i 1.flv";
        p.Start();


        p.WaitForExit();
        string output = p.StandardOutput.ReadToEnd();
        Console.WriteLine(output);
        Console.ReadLine();`

The output string is still empty after the execution of these codes. Plus if I keep the line p.StartInfo.CreateNoWindow = true;, no words will be printed on the console at all, why this happen? I thought the line will only stop a new window being created.

Upvotes: 1

Views: 158

Answers (3)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

I'd try the following:

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;

p.StartInfo.FileName = "ffmpeg.exe";
p.StartInfo.Arguments = " -i 1.flv";
p.Start();

while (!p.HasExited)
{
   string output = p.StandardOutput.ReadToEnd();
}

I also suggest you have a look at the BeginReadOutputLine method in this example given in the MS documentation. Being asynchronous, it will be called even though you use WaitForExit.

A boiled down version of this is:

// Start the asynchronous read of the output stream.
p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
p.EnableRaisingEvents = true;
p.BeginOutputReadLine();
p.Start();
p.WaitForExit();
p.Close();

private static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
    // Collect the command output. 
    if (!String.IsNullOrEmpty(outLine.Data))
    {
        numOutputLines++;

        // Add the text to the output
        Console.WriteLine(Environment.NewLine + 
                "[" + numOutputLines.ToString() + "] - " + outLine.Data);
    }
}

Upvotes: 0

yambe2002
yambe2002

Reputation: 169

How about switch those two line?

p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();

Upvotes: 0

Tsukasa
Tsukasa

Reputation: 6552

Move string output = p.StandardOutput.ReadToEnd(); inside wait for exit. How are you going to read data when it already exit.

    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    //p.StartInfo.CreateNoWindow = true;

    p.StartInfo.FileName = "ffmpeg.exe";
    p.StartInfo.Arguments = " -i 1.flv";
    p.Start();
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();

    Console.WriteLine(output);
    Console.ReadLine();`

Upvotes: 1

Related Questions