.net 如何重定向现有进程的输入和输出c#

niwlg2el  于 2023-01-31  发布在  .NET
关注(0)|答案(1)|浏览(160)

有两个端点,我想添加一个端点来启动进程,另一个端点用来进行进程通信(stdin/stdin),这是可能的吗?或者我应该使用一些其他的方法来做这件事,比如WebSocket?
我正在尝试启动以下过程。

Process process = new Process();

            ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/sh");
            procStartInfo.RedirectStandardError = true;
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.RedirectStandardInput = true;
            procStartInfo.UseShellExecute = false;
            procStartInfo.Arguments = "-c " + Constants.CMDName + args;
            process.StartInfo = procStartInfo;
            Console.WriteLine("Start res: " + process.Start());

进程正在启动,但当我尝试执行下面的stdin/out时,我收到一个错误消息,说StandardIn未重定向。

Process[] processes = Process.GetProcessesByName(Constants.VSDebugProcessName);
        if (processes.Length == 0)
        {
            throw new Exception("Process is not running");
        }
        Console.WriteLine(JsonSerializer.Serialize(processes[0].StartInfo));
        var process = processes[0];
        StreamWriter sw = process.StandardInput;
        await sw.WriteLineAsync(JsonSerializer.Serialize(payload));

我是否应该合并这两个端点,或者是否有其他解决此问题的方法?

neskvpey

neskvpey1#

您可以在ProcessStartInfo中设置EnableRaisingEvents = true,并在进程的OutputDataReceived消息上添加一个处理程序来收集输出。下面的代码片段说明了该过程。它还处理错误输出(stderr)。

var process = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = fileName,
        Arguments = arguments,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        UseShellExecute = false,
    },
    EnableRaisingEvents = true,
};

var output = new StringBuilder();
var error = new StringBuilder();

process.OutputDataReceived += (_, args) =>
{
    output.AppendLine(args.Data);
};

process.ErrorDataReceived += (_, args) =>
{
    error.AppendLine(args.Data);
};

process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
ResultsText.Value = output.ToString();

相关问题