当 运行 来自 C# 的 exe 使用创建进程时,如何模拟 Stdin 输入?

How to mimic Stdin input when running an exe from C# using create process?

我有一个音频转换器 .exe,我想将其包装在 C# 程序中,用于 UI 和输入等。 要使用 AudioConverter.exe,它是来自带有后缀“ouputFile”的控制台的 运行。 所以整行读起来像

C:\User\Audioconverter.exe < song.wav > song.ogg

到目前为止,我已经能够在 C# 之外成功启动转换器,我已经设法通过 C# 中的创建进程使转换器 运行 处于挂起状态(没有输入和输出文件)。 到目前为止,我在 C# 中的代码与此站点上给出的答案非常相似:

using System;
using System.Diagnostics;

namespace ConverterWrapper2
{
    class Program
    {
        static void Main()
        {
            LaunchCommandLineApp();
        }
        static void LaunchCommandLineApp()
        {
            // For the example
            const string ex1 = "C:\Users\AudioConverter.exe";
            const string ex2 = "C:\Users\res\song.wav";
            const string ex3 = "C:\Users\out\song.ogg";

            // Use ProcessStartInfo class
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.CreateNoWindow = false;
            startInfo.UseShellExecute = false;
            startInfo.FileName = "AudioConverter2.exe";
            startInfo.WindowStyle = ProcessWindowStyle.Normal;
            startInfo.Arguments = ex1 + " < " + ex2 + " > " + ex3; \Process is ran successfully without the addition of input and output files, but hangs waiting for files.

            try
            {
                using (Process exeProcess = Process.Start(startInfo))
                {
                    exeProcess.WaitForExit();
                }
            }
            catch
            {
                // Log error.
            }
        }
    }
}

到目前为止,转换器 exe 无法正常启动,这让我想问这个问题,stdin 的输入与参数不同吗?

无论如何,我需要模仿这种输入方式,希望能提供任何信息。我原以为我可以将输入和输出文件作为参数传递,但我运气不佳。

startInfo.Arguments = ex1 + " < " + ex2 + " > " + ex3; \Process is ran successfully without the addition of input and output files, but hangs waiting for files.

那不行。

A.exe < B > C 不是 进程 A.exe 使用参数 < B > C 调用。它更像是一条 shell 指令:

  • 开始 A.exe 没有 参数,
  • 读取文件B并将其内容重定向到新进程的标准输入和
  • 将新进程的标准输出写入文件 C

在 C# 中有两种选择:

  1. 您可以使用 shell 的帮助,即您可以使用参数 /c C:\User\Audioconverter.exe < song.wav > song.ogg

    启动 cmd.exe
  2. 您可以在 C# 中重新实现 shell 正在执行的操作。可以在这个相关问题中找到一个代码示例:

    • redirecting output to the text file c#