使用C#StandardInput重定向时如何将Ctrl + Enter命令传递给Process

时间:2015-02-12 11:38:18

标签: c# process cmd command-line-arguments pos-tagger

我试图制作使用hunpos tagger的C#应用​​程序。 运行hunpos-tag.exe需要三个输入参数:model,inputFile,outputFile

在cmd中它看起来像这样:

hunpos-tag.exe model <inputFile >outputFile

虽然,只有模型可以运行hunpos-tag.exe,但此时它会等待文本输入(来自cmd),当标记器接收Ctrl + Enter作为输入时处理,结果通过标准输出。我一直在尝试在C#中使用StandardInput重定向,但我不知道如何发送Ctrl + Enter结束命令(或者如果重定向完全有效)。代码:

string inputFilePath = path + "\\CopyFolder\\rr";
string pathToExe = path + "\\CopyFolder\\hunpos-tag.exe";

ProcessStartInfo startInfo = new ProcessStartInfo
{
   FileName = pathToExe,
   UseShellExecute = false,
   RedirectStandardInput = true,
   WorkingDirectory = Directory.GetDirectoryRoot(pathToExe),
   Arguments = path + "\\CopyFolder\\model.hunpos.mte5.defnpout",
};
try
{
   Process _proc = new Process();
   _proc.StartInfo.FileName = pathToExe;
   _proc.StartInfo.UseShellExecute = false;
   _proc.StartInfo.RedirectStandardInput = true;
   _proc.StartInfo.Arguments = path + "\\CopyFolder\\model.hunpos.mte5.defnpout";
    _proc.Start();
    var streamReader = new StreamReader(inputFilePath);
    _proc.StandardInput.Write(streamReader.ReadToEnd());
    _proc.StandardInput.Flush();
    _proc.StandardInput.Close();
    _proc.WaitForExit();
}
catch (Exception e)
{
    Console.WriteLine(e);
}

当我运行以下代码时,标记器具有以下输出:

model loaded
tagger compiled
Fatal error: exception Sys_error("Bad file description")

异常是由.Close()命令引起的。该文件有效,在从cmd运行时有效。关于如何发送end命令或如何在不使用重定向的情况下模拟cmd命令的任何想法?

1 个答案:

答案 0 :(得分:0)

它无法使用输入重定向,因此我通过运行cmd procces并将其传递给所需的命令来管理它。

        using (Process process = new Process())
        {
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.WorkingDirectory = @"C:\";
            process.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");

            // Redirects the standard input so that commands can be sent to the shell.
            process.StartInfo.RedirectStandardInput = true;
            // Runs the specified command and exits the shell immediately.
            //process.StartInfo.Arguments = @"/c ""dir""";

            process.OutputDataReceived += ProcessOutputDataHandler;
            process.ErrorDataReceived += ProcessErrorDataHandler;

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            // Send a directory command and an exit command to the shell
            process.StandardInput.WriteLine(path + "\\CopyFolder\\hunpos-tag.exe " + path + "\\CopyFolder\\model.hunpos.mte5.defnpout <" + path + "\\CopyFolder\\rr >" + path + "\\CopyFolder\\zz");
            process.StandardInput.WriteLine("exit");

            process.WaitForExit();
        }