1

I have searched a lot but nothing worked...this code gives me the result when the console ends. but I want real-time output!

  • is there any way to achieve this?
string text1 = "C:/Program Files/Sycho_DL/Downloader.exe -f 242+250 --merge-output-format mp4 -o " + DPath + "/%(title)s.%(ext)s ";
string me2me1 = text1 + urlBoxText2;
ProcessStartInfo startInfo = new ProcessStartInfo();

startInfo.FileName = @"C:/Program Files/Sycho_DL/Downloader.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = me2me1;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;

var process = Process.Start(startInfo);
process.Start();
process.WaitForExit();

while (!process.StandardOutput.EndOfStream)
{
    string line = process.StandardOutput.ReadLine();
    richbox1.Text = line;
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Sycho so
  • 13
  • 3
  • 1
    There are events for that, but for starters, you can just move `process.WaitForExit()` after the loop. – PMF Feb 27 '22 at 19:16
  • @PMF Still gets the last command after the process ends. – Sycho so Feb 27 '22 at 19:20
  • You mean, the last line is only printed after the process exits? There might be a small delay, but that's typically not noticeable, unless you're using the debugger. – PMF Feb 27 '22 at 19:43
  • @PMF nooo it's downloading the video.... and after everything finishes it gives me the last code – Sycho so Feb 27 '22 at 19:46
  • Does https://stackoverflow.com/questions/9533070/how-to-read-to-end-process-output-asynchronously-in-c help? – PMF Feb 27 '22 at 20:06

1 Answers1

2

The System.Diagnostics.Process APIs built into .NET can be difficult to use. I'd suggest using a library that wraps them; my favourite is CliWrap. It has a few different ways to execute external processes, but the "Pull-based event stream" that returns an IAsyncEnumerable would work well here, something like:

using CliWrap;
using CliWrap.EventStream;

var cmd = Cli.Wrap("ExePathGoesHere").WithArguments("ArgumentsGoHere");

await foreach (var cmdEvent in cmd.ListenAsync())
{
    switch (cmdEvent)
    {
        case StandardOutputCommandEvent stdOut:
            // to do: append stdOut.Text to your text box
            break;
        case StandardErrorCommandEvent stdErr:
            // to do: append stdErr.Text to your text box
            break;
        default:
            break;
    }
}
Reilly Wood
  • 1,753
  • 2
  • 12
  • 17
  • i am testing it...but gives this error : https://i.stack.imgur.com/TuNvv.png – Sycho so Mar 03 '22 at 11:04
  • You will need to make the function that is calling this async. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/async – Reilly Wood Mar 03 '22 at 15:45