Run shell command async C#

Tags: csharp

public class ProcessAsync
{

    private string _fileName;
    private string _arguments;

    public ProcessAsync(string fileName, string arguments)
    {
        _fileName = fileName;
        _arguments = arguments;
    }

    public async Task<string> Run()
    {

        var cmd = new Process();
        cmd.StartInfo.FileName = _fileName;
        cmd.StartInfo.RedirectStandardInput = true;
        cmd.StartInfo.RedirectStandardOutput = true;
        cmd.StartInfo.CreateNoWindow = true;
        cmd.StartInfo.UseShellExecute = false;
        cmd.StartInfo.Arguments = _arguments;

        await StartCmdAsync(cmd);

        return cmd.StandardOutput.ReadToEnd();
    }

    private static Task StartCmdAsync(Process cmd)
    {
        var cmdExited = new CmdExitedTask();
        cmd.EnableRaisingEvents = true;
        cmd.Exited += cmdExited.EventHandler;

        cmd.Start();

        return cmdExited.Task;
    }

    private class CmdExitedTask
    {

        private TaskCompletionSource<bool> _tcs
                    = new TaskCompletionSource<bool>();

        public void EventHandler(object sender, EventArgs e)
        {
            _tcs.SetResult(true);
        }

        public Task Task => _tcs.Task;

    }

}

Usage

var p = new ProcessAsync("pandoc", $"\"{filePath}\" -s -o \"{outFile}\"");
Console.WriteLine(await p.Run());