问题描述
我正在写一个包装类的命令行可执行文件。此exe接受从标准输入,直到我在命令提示符下外壳,在这种情况下,根据输入到标准输出打印输出按Ctrl + C。我想模拟在C#code,它CTRL + C preSS,发送kill命令为.NET程序对象。我已经打过电话Process.kill(),但是这似乎并没有给我在这个过程中的StandardOutput StreamReader的东西。可能会有什么,我不这样做对吗?这里的code我试图使用方法:
I'm writing a wrapper class for a command line executable. This exe accepts input from stdin until i hit ctrl+c in the command prompt shell, in which case it prints output based on the input to stdout. I want to simulate that ctrl+c press in c# code, sending the kill command to a .Net process object. I've tried calling Process.kill(), but that doesn't seem to give me anything in the process's StandardOutput StreamReader. Might there be anything I'm not doing right? Here's the code I'm trying to use:
ProcessStartInfo info = new ProcessStartInfo(exe, args);
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);
p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine(scriptcode);
p.Kill();
string error = p.StandardError.ReadToEnd();
if (!String.IsNullOrEmpty(error))
{
throw new Exception(error);
}
string output = p.StandardOutput.ReadToEnd();
但输出始终是空的,即使我得到的数据标准输出回来时,我手动运行exe。
编辑:这是C#2.0 BTW
however output is always empty even though I get data back from stdout when I run the exe manually.edit: this is c# 2.0 btw
推荐答案
我其实只是想出了答案。谢谢大家既为你的答案,但事实证明,我必须做的是这样的:
I've actually just figured out the answer. Thank you both for your answers, but it turns out that all i had to do was this:
p.StandardInput.Close()
这将导致我产生了要完成从标准输入和输出读什么我需要的程序。
which causes the program I've spawned to finish reading from stdin and output what i need.
这篇关于如何发送CTRL + C在C#中的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!