我试图让我的C#wpf应用程序在shell中运行。我的目的是将输出检索到一个字符串,以便我可以解析它。
不幸的是,似乎hg.exe(来自tortoiseHg),不会通过下面的代码返回任何内容。其他.exe似乎有效,如下面的评论所示;
我的代码如下;
`
string workingDir = "";
string filename = "";
string param = "";
//This works
workingDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
filename = "unrar.exe";
param = "";
//this works
workingDir = "c:\\program files\\WinRar";
filename = "unrar.exe";
param = "";
//this works
workingDir = "C:\\Program Files (x86)\\TortoiseHg";
filename = "docdiff.exe";
param = "";
//this does not work. I get a null returned. Why?
workingDir = "C:\\Program Files (x86)\\TortoiseHg";
filename = "hg.exe";
param = "";
//this does not work. I get a null returned. Why?
workingDir = "C:\\Program Files (x86)\\TortoiseHg";
filename = "hg.exe";
param = "help";
string retVal = "";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.WorkingDirectory = workingDir;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.FileName = filename;
proc.StartInfo.Arguments = param;
proc.Start();
System.IO.StreamReader reader = proc.StandardOutput;
retVal = reader.ReadToEnd();
System.Windows.MessageBox.Show(retVal);`
如果有人能说明为什么这段代码不起作用,或者另一种检索mercurial命令行输出的方法,我会非常感激。
谢谢
答案 0 :(得分:1)
您的代码适用于我(使用TortoiseHg 2.0.2测试),前提是我将完整路径传递给可执行文件:
proc.StartInfo.FileName = "C:\\Program Files (x86)\\TortoiseHg\\hg.exe";
答案 1 :(得分:0)
我猜是输出会出现标准错误。
本页讨论如何做到这一点:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx
答案 2 :(得分:0)
我想你可能需要一个
proc.WaitForExit();
在您的阅读结束通话之前?除非该过程是交互式的,否则您会遇到其他问题。
答案 3 :(得分:0)
您可以考虑处理Process.OutputDataReceived和ErrorDataReceived事件:
proc.ErrorDataReceived += delegate(object o, DataReceivedEventHandler e)
{
if (e.Data != null) { /* e.Data is the string from the process */ }
};
proc.OutputDataReceived += delegate(object o, DataReceivedEventHandler e)
{
// ...
};
请务必在开始此过程后致电proc.BeginErrorReadLine()
和proc.BeginOutputReadLine()
。