var p = Process.Start(@"c:PsToolsPsExec.exe", @"C:WindowsSystem32notepad.exe");
var err = p.StandardError.ReadToEnd();
var msg = p.StandardOutput.ReadToEnd();
lblStatusResponse.Text = "Err: " + err + "Msg: " + msg;
为什么我的代码不起作用?
我收到错误:
System.InvalidOperationException: StandardError 尚未重定向。
但是当我添加以下内容时:
p.StartInfo.RedirectStandardError = true;
var p = Process.Start(@"c:PsToolsPsExec.exe", @"C:WindowsSystem32notepad.exe");)
它仍然得到相同的错误。
主要问题是我想执行带有参数的 exe,但我无法让它工作。
以下代码生成一个新的p
,这将忽略您在上一个实例中更改的设置:
var p = Process.Start(@"c:PsToolsPsExec.exe", @"C:WindowsSystem32notepad.exe");)
所以你是否像这样初始化p
并不重要
p.StartInfo.RedirectStandardError = true;
或不。
你需要做什么
您需要创建一个ProcessStartInfo
对象,对其进行配置,然后将其传递给Process.Start
。
ProcessStartInfo p = new ProcessStartInfo(@"c:PsToolsPsExec.exe", @"C:WindowsSystem32notepad.exe");
p.UseShellExecute = false;
p.RedirectStandardError = true;
p.RedirectStandardOutput = true;
Process proc = Process.Start(p);
var err = proc.StandardError.ReadToEnd();
var msg = proc.StandardOutput.ReadToEnd();
自MSDN:https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput(v=vs.110(.aspx
尚未为重定向定义 StandardOutput 流;确保 ProcessStartInfo.RedirectStandardOutput 设置为 true,并将 ProcessStartInfo.UseShellExecute 设置为 false。
因此,请记住按照MS的指示设置这些标志。
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.Arguments = "/C " + command; //Enter your own command
proc.Start();
string output =proc.StandardOutput.ReadToEnd();
这与你拥有的代码不同,但这是我唯一的工作代码,它将在 C# 中运行外部命令/进程,并将所有输出/错误返回到应用程序主窗口
public void Processing()
{
//Create and start the ffmpeg process
System.Diagnostics.ProcessStartInfo psi = new ProcessStartInfo("ffmpeg")
{ // this is fully command argument you can make it according to user input
Arguments = "-y -i '/mnt/Disk2/Video/Antina03.jpg' pp.mp4 ",
RedirectStandardOutput = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError=true,
RedirectStandardInput=true
};
System.Diagnostics.Process ischk;
ischk = System.Diagnostics.Process.Start(psi);
ischk.WaitForExit();
////Create a streamreader to capture the output of ischk
System.IO.StreamReader ischkout = ischk.StandardOutput;
ischk.WaitForExit();
if (ischk.HasExited) // this condition very important to make asynchronous output
{
string output = ischkout.ReadToEnd();
out0 = output;
}
/// in case you got error message
System.IO.StreamReader iserror = ischk.StandardError;
ischk.WaitForExit();
if (ischk.HasExited)
{
string output = iserror.ReadToEnd();
out0 = output;
}
}
如果要运行此过程,只需调用该函数Processing()
BTW out0
是全局变量,以便它可以使用该函数。
信用
我正在使用MonoDevlop"Linux上的C#开发工具",我以这种方式获得输出:-
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
Build();
Processing();
textview2.Buffer.Text = out0;
}