I’ve the below code where I use DevCon.exe to capture something and write it in a file. I parse this file for a need.
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C devcon.exe find = port *monitor* >> monitor_Details.txt";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.Verb = "runas";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
p.WaitForExit();
StreamReader sr = p.StandardOutput;
string log = sr.ReadToEnd();
StreamWriter sw = p.StandardInput;
sw.WriteLine("hi.txt");
p.Close();
Here, I see the txt file being blank all the time. Nothing is written into the text file.
Is there anything wrong? I also checked variable log which gets assigned to
sr.ReadToEnd()
even then log is always blank.
Pl help why shell commands are not getting executed:
CMD shell output redirection within a Process object does not work the way it works in your console shell. The
">>"and"|"are non-functional within a Process context.You will need to run
devcon.exedirectly within Process object instead of wrapping under CMD.EXE. Then capture your output from buffer of the Process object and save it into the txt file if you want the log. Just pass your necessary argument as “find = port *monitor*” as you are doing in your example.MSDN has detailed example and best practices on output buffer capturing. Read here. and here.