How to simulate a keystroke on windowless command line - c#

I'm having trouble with passing a keystroke into a windowless command line.
I start the process as per below:
public partial class BatchRun : Form
{
public void StartProcess(Process name)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = sMasterBATname;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
name.StartInfo = startInfo;
name.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
name.StartInfo.RedirectStandardInput = true;
name.Start();
name.BeginOutputReadLine();
}
}
sMasterBATfile is a batch file which contains number of exe commands to execute. Each exe line is followed by a pause. This is necessary as I need to validate each line which is being redirected and sometimes exe is executed so quickly I have no time to check if it errored or not.
Output is redirected to partial class as per below.
public partial class BatchRun : Form
{
public void outLineValidation(string text)
{
if (text != null && !String.IsNullOrWhiteSpace(text))
{
if (text.Contains("Critical error") || text.Contains("Fatal error"))
{
Do something
}
else if (text.Contains("Complete run time"))
{
This is where I need to pass or
simulate a keystroke to be passed to the process that executes
exe files so that next exe can be executed.
}
}
}
}
I did some research but could not find any that was working for me. All I could find was that I need to bring window forward or pass message etc but not seems to be working.
Could someone help please and explain as if I was a 6 year old please.
Hope this makes sense.

Related

Run a vb script using System.Diagnostics.Process but only partially successful in feeding in input text to the process' stdin

Edit: first things first
The point of the vbscript is to act like a REPL or command prompt/bash
environment, it is simplified to just reprinting the user input
So in other words the cscript process should stay alive and the user input for each pass should be sent to this process only.
And also it means that the internal state of the script should be kept for each pass (One pass = each time the "Send" button in the C# winform is clicked, or in the context of the vbscript, One pass = each time ^Z is input).
For example, if the vbscript is to be modified to demonstrate the state-keeping behavior, you can make the following mods:
At line dim wsh,stmt,l... append it with : dim passcnt : passcnt=1
At line wsh.Echo("Enter lines of strings, press ctrl-z..., replace the last closing bracket with & " (pass #" & passcnt & ")")
At line wsh.Echo("End output") append the code : passcnt = passcnt + 1
Running the vbscript the console will show the pass number incremented on each pass.
The C# winform can be modified in any way, as long as the above condition still holds.
Try to observe what the script does by cscript ask_SO.vbs, it should make things clear enough
I think this is the most clear I am able to made it.
I would like to use stdout/stdin redirection of System.Diagnostics.Process to feed input texts to the following VBScript.
What the vbscript does is that it allows the user to input multiple lines of strings to the console, and when the ^z character is input, the script will just output everything ver batim to the console:
Sample Output
Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.
Enter lines of strings, press ctrl-z when you are done (ctrl-c to quit):
I come with no wrapping or pretty pink bows.
got line
I am who I am, from my head to my toes.
got line
I tend to get loud when speaking my mind.
got line
Even a little crazy some of the time.
got line
I'm not a size 5 and don't care to be.
got line
You can be you and I can be me.
got line
got line
Source: https://www.familyfriendpoems.com/poem/be-proud-of-who-you-are
got line
^Z
=====================================
You have entered:
I come with no wrapping or pretty pink bows.
I am who I am, from my head to my toes.
I tend to get loud when speaking my mind.
Even a little crazy some of the time.
I'm not a size 5 and don't care to be.
You can be you and I can be me.
Source: https://www.familyfriendpoems.com/poem/be-proud-of-who-you-are
End output
Enter lines of strings, press ctrl-z when you are done (ctrl-c to quit):
After that, the user can input another chunk of text and repeat the process.
This is the script code:
ask_SO.vbs
dim wsh,stmt,l : set wsh = WScript
do
wsh.Echo("Enter lines of strings, press ctrl-z when you are done (ctrl-c to quit):")
'stmt=wsh.StdIn.ReadAll()
do
l=wsh.StdIn.ReadLine()
wsh.echo("got line")
stmt = stmt & l & vbcrlf
loop while (not wsh.StdIn.AtEndOfStream)
wsh.Echo("=====================================")
wsh.Echo("You have entered:")
wsh.Echo(stmt)
wsh.Echo("End output")
loop
This is how to invoke the script:
cscript ask_SO.vbs
I came out with the following C# code (project type set to Console Application instead of Windows Forms):
frmPostSample
public class frmPostSample : Form
{
Process proc_cscr;
StreamWriter sw;
public frmPostSample()
{
InitializeComponent2();
}
#region Copied from generated code
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent2()
{
this.txt_lines = new System.Windows.Forms.TextBox();
this.Btn_Send = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// txt_lines2
//
this.txt_lines.Location = new System.Drawing.Point(41, 75);
this.txt_lines.Multiline = true;
this.txt_lines.Name = "txt_lines2";
this.txt_lines.Size = new System.Drawing.Size(689, 298);
this.txt_lines.TabIndex = 0;
//
// Btn_Send2
//
this.Btn_Send.Location = new System.Drawing.Point(695, 410);
this.Btn_Send.Name = "Btn_Send2";
this.Btn_Send.Size = new System.Drawing.Size(75, 23);
this.Btn_Send.TabIndex = 1;
this.Btn_Send.Text = "&Send";
this.Btn_Send.UseVisualStyleBackColor = true;
this.Btn_Send.Click += new System.EventHandler(this.Btn_Send_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.Btn_Send);
this.Controls.Add(this.txt_lines);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.TextBox txt_lines;
private System.Windows.Forms.Button Btn_Send;
#endregion
private void Btn_Send_Click(object sender, EventArgs e)
{
if (proc_cscr == null)
{
if (!File.Exists("ask_SO.vbs"))
{
MessageBox.Show("Script file not exist");
return;
}
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cscript";
startInfo.Arguments = "//nologo ask_SO.vbs";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
proc_cscr = new Process();
proc_cscr.StartInfo = startInfo;
proc_cscr.Start();
sw = proc_cscr.StandardInput;
}
OutPrint();
foreach (var vbsline in txt_lines.Lines)
{
sw.WriteLine(vbsline); // <-------- SW WRITELINE
sw.Flush();
OutPrint();
}
//sw.Flush();
sw.Close();
while (true)
{
var s2 = proc_cscr.StandardOutput.ReadLineAsync();
s2.Wait();
Console.WriteLine(s2.Result);
if (proc_cscr.StandardOutput.Peek() == -1) break;
}
}
private void OutPrint()
{
string l;
while (proc_cscr.StandardOutput.Peek() != -1)
{
l = proc_cscr.StandardOutput.ReadLine();
Console.WriteLine(l);
}
}
}
Run the program, and if you have correctly set the project type to "Console Application", a console window and a GUI Window should be shown.
You just paste the text to the text input area and press send, and observe the result in the console window.
However, what the C# form behaves is not the same as directly running the script cscript ask_SO.vbs:
The script can only accept one pass of input - the second pass throws the error "Cannot write to a closed TextWriter" at the line with comment SW WRITELINE - I know it is because I've closed the stdin stream, but otherwise I can't make the script go forward
Also, I've got the error shown: ...\ask_SO.vbs(8, 9) Microsoft VBScript runtime error: Input past end of file.
The "got line" echo is not shown immediately after the c# code write a line input to the stdin (again, at the line with comment SW WRITELINE).
I've searched online to find a solution, but most of the materials only shows input without using the ^z character, or in other words, only accepts one-pass input.
You can download the C# visual studio solution here (vbscript included - you just load the solution in visual studio 2019 and press F5 to run).
Note
The encoding I got from proc_cscr.StandardOutput.CurrentEncoding.BodyName and proc_cscr.StandardInput.Encoding.BodyName is big5, it is a DBCSCodePageEncoding, used for encoding Chinese characters.
I recognized that I need to mention this, when I tried the suggestion mentioned in an answer to write (char)26 to the stdin stream. As Encoding.GetEncoding("big5").GetBytes(new char[]{(char)26}) returns only one byte (two bytes for unicode: {byte[2]} [0]: 26 [1]: 0), I did a sw.Write((char)26);, and add a sw.flush() also. It still didn't work.
I do not think, this is possible to do.
Your point 3:
The "got line" echo is not shown immediately after the c# code write a line input to the stdin
This is because you have redirected output (startInfo.RedirectStandardOutput = true). If you redirect it, everything you write goes to the StandardOutput stream and you have to read it manually. So just do not redirect output and your got line messages will be immediate. If the output is not redirected, you can not use StandardOutput property (but you do not need it anyway).
The rest is more difficult. The thing is, it seems there is not a way how to send end of stream, because this is what stops your inner loop in vbs. The stream ends when you finish with it - technically when you close it, or finish your process. The character of value 26 is represented as end of stream (Ctrl + Z) somewhere. But it is not working here (I tried sw.Write(Convert.ToChar(26)).
I do not know if it is possible (I do not know vbs), but maybe you can change your logic there and not check for end of stream. Insted of it maybe read by bytes (characters) and check for specific char (for example that char(26)) to step out of the inner loop.
Your problem here is when you close the stream, cscript also terminates and you try to read from a dead process.
I've modified your sample to utilize async reading of cscript by calling BeginOutputReadLine and reading output in OutputDataReceived event. I've also added a WaitForExit which is required to ensure raising of async events.
By the way you really do not need to send CTRL+Z since it is just a character and it is not really the EOF marker. Console handler just handles that keystroke as EOF signal. Closing StandardInput does the trick.
var psi = new ProcessStartInfo
{
FileName = "cscript",
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
//CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Normal,
Arguments = "//nologo ask_SO.vbs"
};
var process = Process.Start(psi);
process.BeginOutputReadLine();
var buffer = new StringBuilder();
process.OutputDataReceived += (s, args) =>
{
buffer.AppendLine(args.Data);
};
foreach (var line in textBox1.Lines)
{
buffer.AppendLine(line);
process.StandardInput.WriteLine(line);
Thread.Sleep(50);
}
process.StandardInput.Flush();
process.StandardInput.Close();
process.WaitForExit();
output.Text = buffer.ToString();
EDIT: Updated to keep process alive
private Process process;
private void EnsureProcessStarted()
{
if (null != process)
return;
var psi = new ProcessStartInfo
{
FileName = "cscript",
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
//CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Normal,
Arguments = "//nologo ask_SO.vbs"
};
process = Process.Start(psi);
process.OutputDataReceived += (s, args) => AppendLineToTextBox(args.Data);
process.BeginOutputReadLine();
// time to warm up
Thread.Sleep(500);
}
private void AppendLineToTextBox(string line)
{
if (string.IsNullOrEmpty(line))
return;
if (output.InvokeRequired)
{
output.Invoke(new Action<string>(AppendLineToTextBox), line);
return;
}
output.AppendText(line);
output.AppendText(Environment.NewLine);
}
private void SendLineToProcess(string text)
{
EnsureProcessStarted();
if (string.IsNullOrWhiteSpace(text))
{
process.StandardInput.Flush();
process.StandardInput.Close();
//process.WaitForExit(); causes a deadlock
process = null;
}
else
{
AppendLineToTextBox(text); // local echo
process.StandardInput.WriteLine(text);
process.StandardInput.Flush();
// time to process
Thread.Sleep(50);
}
}

Reading StandardOutput of .NET Process on demand

I'm working on a mechanism, that's capable of creating a Process with a script running on it. At certain points I'm sending input via StandardInput.WriteLine() to that script, which causes it to display information. I want to retrieve only the portion of output, that was displayed between inputs.
for eg.
"some text"
Username: <- there we send the input via StandardInput, and cause script to write some data
"THIS IS THE PORTION OF OUTPUT I WANT TO RETRIEVE"
Password: <- we send another input via StandardInput, I don't want to retrieve this.
"some more text"
I tried using OutputDataReceived event, but it does not fire as expected (I thought it'll fire when I pass input to the script, causing it to spit data).
Can you guys help me come with a solution?
This is the previous try with OutputDataReceived approach.
public ctor()
{
this.outputStringsList = new List<string>();
this.process = new Process();
this.process.StartInfo = this.GetProcessStartInfo();
this.process.OutputDataReceived += onOutputDataReveived;
this.process.Start();
this.process.BeginOutputReadLine();
}
private void onOutputDataReveived(object sender, DataReceivedEventArgs e)
{
var data = e.Data;
this.outputStringsList.Add(data);
}
private ProcessStartInfo GetProcessStartInfo()
{
var start = new ProcessStartInfo();
start.UseShellExecute = false;
start.CreateNoWindow = true;
start.RedirectStandardInput = true;
start.RedirectStandardOutput = true;
return start;
}
public void PassArg(string arg)
{
this.process.StandardInput.WriteLine(arg);
}
It does indeed return output from the process, but it's not on demand

How to redirect output from the NASM command line assembler in C#

Brief Summary
I am creating a lightweight IDE for NASM development in C# (I know kind of an irony). Kinda of like Notepad++ but simpler but with features that make it more than source editor. Since Notepad++ is really just a fancy source editor. I have already implemented features like Project creation (using a project format similar to how Visual Studio organizes projects). Project extension .nasmproj. I am also in the works of hosting it in an open-source place (Codeplex). Although the program is far from finish, and definitely cannot be used in a production environment without proper protection and equipment. In addition, I am working alone with it at this moment, more like a spare time project since I just finished my last Summer final taking Calculus I.
Problem
Right now I am facing a problem, I can build the project but no output from NASM is being fed into the IDE. I have succesfully built a project, and I was able to produce object files. I even tried producing a syntax error to see if I finally see something come up but none and I check the bin folder of the test project I created and I see no object file creating. So definitely NASM is doing its magic. Is it because NASM doesn't want me to see its output. Is there a solution? Any advice would be great. Here is the code which I think is giving Trouble.
Things to Note
I have already checked if events have been invoked. An yes they have but they return empty strings
I have also checked error data and same effect.
Code
public static bool Build(string arguments, out Process nasmP)
{
try
{
ProcessStartInfo nasm = new ProcessStartInfo("nasm", arguments);
nasm.CreateNoWindow = true;
nasm.RedirectStandardError = true;
nasm.RedirectStandardInput = true;
nasm.RedirectStandardOutput = true;
nasm.UseShellExecute = false;
nasmP = new Process();
nasmP.EnableRaisingEvents = true;
nasmP.StartInfo = nasm;
bool predicate = nasmP.Start();
nasmP.BeginOutputReadLine();
return true;
}
catch
{
nasmP = null;
return false;
}
}
//Hasn't been tested nor used
public static bool Clean(string binPath)
{
if (binPath == null || !Directory.Exists(binPath))
{
throw new ArgumentException("Either path is null or it does not exist!");
}
else
{
try
{
DirectoryInfo binInfo = new DirectoryInfo(binPath);
FileInfo[] filesInfo = binInfo.GetFiles();
for (int index = 0; index < filesInfo.Length; index++)
{
try
{
filesInfo[index].Delete();
filesInfo[index] = null;
}
catch
{
break;
}
}
GC.Collect();
return true;
}
catch
{
return false;
}
}
}
}
using (BuildDialog dlg = new BuildDialog(currentSolution))
{
DialogResult result = dlg.ShowDialog();
dlg.onOutputRecieved += new BuildDialog.OnOutputRecievedHandler(delegate(Process _sender, string output)
{
if (result == System.Windows.Forms.DialogResult.OK)
{
outputWindow.Invoke(new InvokeDelegate(delegate(string o)
{
Console.WriteLine("Data:" + o);
outputWindow.Text = o;
}), output);
}
});
}
Edits
I have tried doing synchronously instead of asynchronously but still the same result (and empty string "" is returned) actually by debugging the stream is already at the end. So looks like nothing has been written into the stream.
This is what I tried:
string readToEnd = nasmP.StandardOutput.ReadToEnd();
nasmP.WaitForExit();
Console.WriteLine(readToEnd);
And another interesting thing I have tried was I copied the arguments from the debugger and pasted it in the command line shell and I can see NASM compiling and giving the error that I wanted to see all along. So definitely not a NASM problem. Could it be a problem with my code or the .Net framework.
Here is a nice snapshot of the shell window (although not technically proof; this is what the output should look like in my IDE):
Alan made a very good point, check the sub processes or threads. Is sub process and thread synonymous? But here is the problem. Almost all the properties except a select few and output/error streams are throwing an invalid operation. Here is the debugger information as an image (I wish Visual Studio would allow you to copy the entire information in click):
Okay I finally was able to do it. I just found this control that redirect output from a process and I just looked at the source code of it and got what I needed to do. Here is the the modified code:
public static bool Build(string command, out StringBuilder buildOutput)
{
try
{
buildOutput = new StringBuilder();
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
startInfo.Arguments = "/C " + " nasm " + command;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process p = Process.Start(startInfo);
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
p.WaitForExit();
if (output.Length != 0)
buildOutput.Append(output);
else if (error.Length != 0)
buildOutput.Append(error);
else
buildOutput.Append("\n");
return true;
}
catch
{
buildOutput = null;
return false;
}
}
Here is how the output is formatted like:
I also wanted to thank Alan for helping me debug my code, although he didn't physically had my code. But he really was helpful and I thank him for it.

how to find out the path of the program using c#

I found a snippet of code explaining how to use System.Diagnostics.Process.Start to run an external program in C#. The snippet shows running cmd.exe, which is in the path.
Let's assume that there is some external program (Beyond Compare for example). I don't know if it is installed on the PC. How can I check if this program is installed using C#? If the program is installed, I would like to find the path so that I can launch it.
I found this question, which directed me to this this article.
I've modified the source for readability, and to solve your problem specifically (note that I've guessed the description and executable name of Beyond Compare.)
You can call it like this, from your main:
string path = FindAppPath("Beyond Compare");
if (path == null)
{
Console.WriteLine("Failed to find program path.");
return;
}
path += "BeyondCompare.exe";
if (File.Exists(path))
{
Process beyondCompare = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = path + "BeyondCompare.exe",
Arguments = string.Empty // You may need to specify args.
}
};
beyondCompare.Start();
}
The source for FindAppPath follows:
static string FindAppPath(string appName)
{
// If you don't use contracts, check this and throw ArgumentException
Contract.Requires(!string.IsNullOrEmpty(appName));
const string keyPath =
#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath))
{
var installed =
(from skName in key.GetSubKeyNames()
let subkey = key.OpenSubKey(skName)
select new
{
name = subkey.GetValue("DisplayName") as string,
path = subkey.GetValue("InstallLocation") as string
}).ToList();
var desired = installed.FindAll(
program => program.name != null &&
program.name.Contains(appName) &&
!String.IsNullOrEmpty(program.path));
return (desired.Count > 0) ? desired[0].path : null;
}
}
Keep in mind that this method returns the first matching path, so don't feed it an appName argument that's too generic (eg. "Microsoft") or you probably won't get what you're looking for.
Well, if you're trying to see if a program exists where you're looking for it (like BeyondCompare.exe), you can just use a call to:
System.IO.File.Exists("path_to_program.exe");
If it returns true, then you know your program exists and you can run it with your process runner code. If it returns false, then you know it's not there and you shouldn't launch your process.
If I'm misunderstanding your question, please let me know and I'll update my answer accordingly.
Thanks. Hope this helps!
Simple logic to do for this.
string filepath = "c:\windows\test.exe";
bool bOk = false;
try
{
bOk = System.IO.File.Exists(filepath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
if (!bOk)
{
Console.WriteLine("Error: Invalid Path");
}
else
{
Process p = new Process();
p.StartInfo.FileName = filepath;
p.StartInfo.Arguments = "/c dir *.cs";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine("Output:");
Console.WriteLine(output);
}
Are you sure you don't need to make that check. Simply start the program without path (only the filename) and set ProcessStartInfo.UseShellExecute = true.
Windows will look for the app in its list of installed app. If it doesn't find it, Process.Start()will fail. The interesting thing is that you never had to care about where the app is stored.

Capture output of process synchronously (i.e. "when it happens")

I am trying to start a process and capture the output, have come a far way, but am not quite at the solution I'd want.
Specifically, I am trying to reset the IIS on my development machine from a small utility application that I am writing. I have come to the conclusion, by experimenting, that the safe way to do this is by running iisreset.exe in a child process.
If you run iisreset.exe on a command prompt, you get feedback during the process. Running iisreset takes several seconds, and several lines of feedback is generated, with pauses in between.
I'd like to capture this feedback and present it in my Windows Forms application (in a ListBox), and I have succeeded with that. My remaining concern is that I dont get it until the child process finishes. I'd like to get the output from the child process, line by line, immediately when the lines are created.
I have tried to do my homework, reading/testing things from e.g. these:
How to spawn a process and capture its STDOUT in .NET?
Capturing console output from a .NET application (C#)
http://www.aspcode.net/ProcessStart-and-redirect-standard-output.aspx
and several more with similar content. Most (all?) get the output asynchronously (e.g. with Process.ReadToEnd()). I want the output synchonously, which acording to the MSDN documentation involves establishing an event handler etc and I've tried that. It works, but the event handler does not get called until the process exits. I get the output from iisreset.exe, but not until it has finished.
To rule out the possibility that this has something to do with iisreset.exe in particular, I wrote a small console application that generates some output, pausing in between:
namespace OutputGenerator
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("OutputGenerator starting and pausing for 10 seconds..");
System.Threading.Thread.Sleep(10000);
System.Console.WriteLine("Pausing for another 10 seconds..");
System.Threading.Thread.Sleep(10000);
System.Console.WriteLine("Exiting!");
}
}
}
Testing with this it turns out that I get captured data diretly when I want. So, to some extent it seems that the way iisreset.exe outputs the data come into play here.
Here is the code of the program (a Windows Forms application) that does the capture:
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace OutputCapturer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnRun_Click(object sender, EventArgs e)
{
// Running this will show all output after the process has exited
//String path = #"C:\Windows\system32\iisreset.exe";
// Running this will show all output "when it happens"
String path = #"C:\OutputGenerator.exe";
var p = new Process();
p.StartInfo.FileName = path;
p.StartInfo.UseShellExecute = false; // ShellExecute = true not allowed when output is redirected..
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.OutputDataReceived += OutputDataReceived;
p.Start();
p.BeginOutputReadLine();
}
private delegate void OutputDataToTextboxDelegate(String s);
void OutputDataToTextbox(String s)
{
tbxOutput.Text += s + Environment.NewLine;
tbxOutput.Refresh();
}
private void OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null && e.Data.ToString() != "")
{
// Must run the update of the textbox in the same thread that created it..
tbxOutput.Invoke(
new OutputDataToTextboxDelegate(OutputDataToTextbox),
DateTime.Now.ToString() + ": " + e.Data.ToString()
);
}
}
}
}
Thinking it was an EOL-encoding problem (the output of iisreset.exe apearing as one line to my app)), I ran a debug session. Nope. The event handler for StandardOutput gets called several times (one time for each output line from iisreset.exe), buth these calls come in one burst after the process exits.
I would LOVE if I could get the output from iisreset.exe "when it happens" so that I can show it as a progress indication.
I've seen one other thread with the same/similar problem, Asynchronous capture from a process output not working properly , but w/o a solution.
I'm sort of stumped.
To do autoflushing of printfs / stdouts
C equivalent of autoflush (flush stdout after each write)?
This saved my ass...
It seems that sixlettervariables is correct, and that this has something to do with iisreset.exe isn't flushing it's buffers for each line. (I still wonder what makes it work on a plain command line - i.e. what does cmd.exe do?)
Anyhow.. I tried what apacay suggested, and wrote this:
private void btnRun_Click(object sender, EventArgs e)
{
// Running this will show the output after the process has finished
//String path = #"C:\Windows\system32\iisreset.exe";
// Running this will show all output "when it happens"
String path = #"C:\OutputGenerator.exe";
var p = new Process();
p.StartInfo.FileName = path;
p.StartInfo.UseShellExecute = false; // ShellExecute = true not allowed when output is redirected..
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
StreamReader sr = p.StandardOutput;
while (!sr.EndOfStream)
{
String s = sr.ReadLine();
if (s != "")
{
tbxOutput.Text += DateTime.Now.ToString() + ": " + s + Environment.NewLine;
}
tbxOutput.Refresh();
}
}
Notice that I am timestamping when I get each line. For my OutputGenerator I get this:
2011-07-06 17:49:11: OutputGenerator starting and pausing for 10 seconds..
2011-07-06 17:49:21: Pausing for another 10 seconds..
2011-07-06 17:49:31: Exiting!
And for iisreset.exe I get this:
2011-07-06 17:57:11: Attempting stop...
2011-07-06 17:57:11: Internet services successfully stopped
2011-07-06 17:57:11: Attempting start...
2011-07-06 17:57:11: Internet services successfully restarted
Running iisreset.exe on the command line, those lines come with pauses in between, over a span of perhaps 10 seconds.
The case seems more or less closed now. Not that I am all that satisfied, but I'm at roads end it seems. I'll reluctantly live with it..
To summarise: In the general case, it is quite possible to capture output synchronously with when it is generated. This thread presents code for two ways to do that - by establishing an event handler, and by "polling" the stream. In my specific case there is something with how iisreset.exe generates output that prevents this.
Thanks to those who participated and contributed!
Well.... you could kick it old-school. Output can be redirected to the input of another program using old-school DOS commands (foo.exe | bar.exe). Write a program that reads from standard in, and you'll get it every time the stream flushes.
Edit
You could also redirect the ouput to a named pipe and read from that. That would also be "as it happens".
Well, I tried a helper class that I know works: http://csharptest.net/browse/src/Library/Processes/ProcessRunner.cs
ProcessRunner runner = new ProcessRunner("iisreset.exe");
runner.OutputReceived += OutputDataReceived;
runner.Start("/RESTART", "/STATUS");
However, this still doesn't solve the problem with this specific executable. It seems that iisreset was written in such a way that this is not possible. Even running the following from the command line:
iisreset.exe /RESTART /STATUS > temp.txt
Still nothing is written to the text file 'temp.txt' until after all services have been restarted.
As for your example code, I would recommend reading a post I wrote some time ago: How to use System.Diagnostics.Process correctly. Specifically you are not reading the std::err stream or redirecting and closing the std::in stream. This can cause very undesirable results in your program. You can look at the example wrapper class linked above for how to do it with the output events, or if you want to directly read the streams you need to use two of your own threads.
static void Main()
{
ProcessStartInfo psi = new ProcessStartInfo(#"C:\Windows\system32\iisreset.exe", "/RESTART /STATUS");
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
ManualResetEvent output_complete = new ManualResetEvent(false);
ManualResetEvent error_complete = new ManualResetEvent(false);
Process p = Process.Start(psi);
new ReadOutput(p.StandardOutput, output_complete);
new ReadOutput(p.StandardError, error_complete);
p.StandardInput.Close();
p.WaitForExit();
output_complete.WaitOne();
error_complete.WaitOne();
}
private class ReadOutput
{
private StreamReader _reader;
private ManualResetEvent _complete;
public ReadOutput(StreamReader reader, ManualResetEvent complete)
{
_reader = reader;
_complete = complete;
Thread t = new Thread(new ThreadStart(ReadAll));
t.Start();
}
void ReadAll()
{
int ch;
while(-1 != (ch = _reader.Read()))
{
Console.Write((char) ch);
}
_complete.Set();
}
}
I wrote this just to see if anything was coming through. Still got nothing until the end, so I think your just SOL on getting asynchronous output from iisreset.
I've had that problem and had to solve it when my logs where too long to read in a single readtoend.
This is what I've done to solve it. It's been doing Ok so far.
myProcess.StartInfo.FileName = path;
myProcess.StartInfo.Arguments = args;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.ErrorDialog = false;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.StartInfo.RedirectStandardInput = (stdIn != null);
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.Start();
int index;
OpenLogFile(myLog); //LOGGGGGGGGGGGGG
if (myProcess.StartInfo.RedirectStandardInput)
{
StreamWriter sw = myProcess.StandardInput;
sw.Write(stdIn + Convert.ToChar(26));
}
StreamReader sr = myProcess.StandardOutput;
/*stdOut = new ArrayLi
*/
while (!sr.EndOfStream)
{ //LOGGGGGGGGGGGGG
Log(sr.ReadLine(), true);
}
Here's OpenLogFile
private void OpenLogFile(string fileName)
{
if (file == StreamWriter.Null)
{
file = new StreamWriter(fileName, true);
file.AutoFlush = true;
}
}
Of course that Log is a function that does something elsewhere. But the solution to you question lies here:
while (!sr.EndOfStream)
{ //LOGGGGGGGGGGGGG
Log(sr.ReadLine(), true);
}
while stream reader is still reading, you can be writing it down as the log comes out.
For my specific situation, the solution is what Mr Moses suggested in a comment above, i.e. run iisreset /stop followed by iisreset /start.
I need a proper answer, rather than a comment, in order to mark it as my "accepted answer", so this answer is more of administrativa than a new contribution. The cred should go to Mr Moses.. :-)

Categories

Resources