首页 > 解决方案 > 使用创建进程从 C# 运行 exe 时如何模仿标准输入?

问题描述

我有一个音频转换器 .exe,我想将它封装在 C# 程序中,用于 UI 和输入等。要使用 AudioConverter.exe,它是从带有后缀“< inputFile > 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 无法正确启动,这让我问这个问题是标准输入的输入与参数不同吗?

无论如何,我都需要模仿这种输入方式,并且会很感激任何信息。我曾假设我可以将输入和输出文件作为参数传递,但我运气不佳。

标签: c#stdinoggvorbis

解决方案


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 的帮助,即,您可以从cmd.exe参数开始/c C:\User\Audioconverter.exe < song.wav > song.ogg

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


推荐阅读