Saving Standard Output in memory instead of a file in C#

1.2k views Asked by At

There is no online tutorial or even a book, for handling Standard Output with C#.

I want to save standard output in a variable (memory) instead of a file in Shell Execution.

This for storing thumbnail image from a video file with ffmpeg.

The below is my code.

public static void GetThumbnail(string video, string thumbnail, string ffdir)
{
    var cmd = " -ss 00:01:00.000 -i " + '"' + video + '"' + " -vcodec rawvideo -vframes 1 -an -f rawvideo -s 320x240 pipe:1 ";


    var startInfo = new ProcessStartInfo
    {
        WindowStyle = ProcessWindowStyle.Normal,
        FileName = ffdir + "\\ffmpeg.exe ",
        Arguments = cmd,
        RedirectStandardOutput = true,
        UseShellExecute = false
    };

    var process = new Process
    {
        StartInfo = startInfo
    };

    process.OutputDataReceived += ProcessOnOutputDataReceived;
    process.ErrorDataReceived += ProcessOnOutputDataReceived;

    process.Start();

    process.WaitForExit(1000);
}

private static void ProcessOnOutputDataReceived(object sender, DataReceivedEventArgs dataReceivedEventArgs)
{
    ....
}

But it does not enter to the event handler function (ProcessOnOutputDataReceived) when GetThumbnail function launched.

Is there any clue to solve this problem?

I referred the question and answer here: getting mulitple images from a single stream piped from ffmpeg stdout

But it does not help. It seems that the code for previous .NET versions.

2

There are 2 answers

0
user On

You can save it in a string.

var content = process.StandardOutput.ReadToEnd();

Or if it's asynchronous, I guess you could use a String Builder and check the OutputStream somewhere else.

0
Mark Hurd On

You need

process.BeginOutputReadLine();
process.BeginErrorReadLine();

This question is effectively a duplicate.