Why is this C # code not working? I am trying to read shell output in TortoiseHG (Mercurial)

I am trying to get mercurial to run in a shell from my C # wpf application. My goal is to extract the output to a string so that I can parse it.

Unfortunately, it seems to me that hg.exe (from tortoiseHg) does not return anything through the code below. Other .exe seem to work as seen in the comments below;

My code is below;

`

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);` 

If anyone can guess why this code is not working, or alternatively another way to get mercurial command line output, I would really appreciate it.

thanks

+2
c # mercurial tortoisehg
source share
4 answers

Your code works for me (tested with TortoiseHg 2.0.2), provided that I pass the full path to the executable:

 proc.StartInfo.FileName = "C:\\Program Files (x86)\\TortoiseHg\\hg.exe"; 
+1
source share

I assume there is a way out going to standard error.

This page talks about how to do this:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx

0
source share

I think you may need

 proc.WaitForExit(); 

before reading? If the process is not interactive, you have another problem.

0
source share

You might want to handle the Process.OutputDataReceived and ErrorDataReceived events:

 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) { // ... }; 

Be sure to call proc.BeginErrorReadLine() and proc.BeginOutputReadLine() after starting the process.

0
source share

All Articles