External EXE's Output is Blank (or at least appears) - c#

Pretty new to C#, I'm trying to create a WinForms Application that will run ScanState and capture the output from it. I've got this code as a test...
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = $"amd64\\scanstate.exe"; ;
process.StartInfo.Arguments = "";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
string q = "";
string err = "";
while (!process.HasExited)
{
q += process.StandardOutput.ReadToEnd();
err += process.StandardError.ReadToEnd();
}
//label1.text = q;
MessageBox.Show(q.ToString());
MessageBox.Show(err);
}
But all I get is two blank message boxes.
Inspecting q shows that apparently it says something.
The inspector says this:
\r\0\n\0s\0t\0r\0a\0t\0o\0r\0 \0p\0r\0i\0v\0i\0l\0e\0g\0e\0s\0 \0a\0r\0e\0 \0r\0e\0q\0u\0i\0r\0e\0d\0 \0t\0o\0 \0r\0u\0n\0 \0t\0h\0i\0s\0 \0t\0o\0o\0l\0.\0\r\0\n\0\r\r\nScanState return code: 34\r\r\n"
I'm not sure what this is or if it can even be converted to plain text.

Related

How to get the the result of batch file to C#

I am currently struggling with bringing existing data in batch file to C# window form
The whole objective is getting a result lively from batch file to C# rich text box but I am keep getting failure of doing it.
The procedure works like click button->run batch file secretly->C# gets data lively->display in rich text box
I was successful to run a batch file but it runs in another new CMD causing hanging problem during debugging.
I would like to know whether anyone can wrote me a code to overcome such problem. Hope for the best answer
ProcessStartInfo cmd = new ProcessStartInfo();
Process process = new Process();
cmd.FileName = #"cmd";
cmd.UseShellExecute = false;
cmd.RedirectStandardError = true;
cmd.RedirectStandardInput = true;
cmd.RedirectStandardOutput = true;
cmd.CreateNoWindow = true;
process.EnableRaisingEvents = false;
process.StartInfo = cmd;
process.Start();
process.StandardInput.Write(#"cd C:\Users\%username%\Desktop\Claymore's Dual Ethereum+Decred_Siacoin_Lbry_Pascal AMD+NVIDIA GPU Miner v11.0" + Environment.NewLine);
process.StandardInput.Write(#"EthDcrMiner64.exe -allpools 1 -epool asia1.ethereum.miningpoolhub.com:20535 -ewal AJStudio.AJStudio001 -epsw x -esm 2" + Environment.NewLine);
process.StandardInput.Close();
string result = process.StandardOutput.ReadToEnd();
StringBuilder sb = new StringBuilder();
sb.Append("[result info]" + DateTime.Now + "\r\n");
sb.Append(result);
sb.Append("\r\n");
richTextBox1.Text = sb.ToString();
process.WaitForExit();
process.Close();
To get real-time feedback from Process, use OutputDataReceived and ErrorDataReceived events. Something like this:
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.OutputDataReceived += Process_OutputDataReceived;
process.ErrorDataReceived += Process_ErrorDataReceived;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null) return;
log("ERROR: " + e.Data);
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null) return;
log(e.Data);
}

User enter the command programmatically in the cmd

I want to build a windows application that can prompt CMD. However I would like to enable user enter the command programmatically. As in my code below, I enable to called CMD but the command (e.g. ipconfig) is only hardcoded. I want user to enter other command.
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.StandardInput.WriteLine("ipconfig");
process.StandardInput.Flush();
process.StandardInput.Close();
process.WaitForExit();
string s = process.StandardOutput.ReadToEnd();
richTextBox1.Text = s;
}
You can do this....
// you can populate command from user input
String command = "ipconfig";
// or
command = userTxt.Text;
process.StandardInput.WriteLine(command );

How to get the cmd command output in c# to a lable

I wrote a code for run cmd commands from c# form application. Now I want to get the output of the cmd to a lable in winform. I wrote a code. but it is giving me following error
Screenshot of the Error
An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll
Additional information: StandardOut has not been redirected or the process hasn't started yet.
how to fix it? this is my original code.
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startiNFO = new System.Diagnostics.ProcessStartInfo();
startiNFO.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startiNFO.FileName = "cmd.exe";
startiNFO.Arguments = "/C ipconfig";
startiNFO.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo = startiNFO;
process.Start();
string outp = process.StandardOutput.ReadToEnd();
process.WaitForExit();
MessageBox.Show(outp);
}
instead of process.WaitForExit(); do something like this
The complete code for your function would look something like this
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C ipconfig";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
string q = "";
while(!process.HasExited)
{
q += process.StandardOutput.ReadToEnd();
}
label1.text = q;
MessageBox.Show(q);
}

Reading cmd output real time

I'm writing a program that reads python script output and shows the results in textbox.
Since the script runnning for a long time, I want to be able to see the output every 1 second (or after each line is writen).
Now i can see the output only when the process ends.
Does someone know what is the problem?
snippet of my code:
Process p = new Process();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.OutputDataReceived += new DataReceivedEventHandler (p_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler (p_ErrorDataReceived);
p.Exited += new EventHandler (p_Exited);
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "python.exe";
p.StartInfo.Arguments = "path " + commandline;
p.Start();
StreamReader s = p.StandardOutput;
String output = s.ReadToEnd();
textBox3.Text = output;
p.WaitForExit();
I'm doing it the following way in my own programs:
private static void startProgram(
string commandLine )
{
var fileName = commandLine;
var arguments = string.Empty;
checkSplitFileName( ref fileName, ref arguments );
var info = new ProcessStartInfo();
info.FileName = fileName;
info.Arguments = arguments;
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
using ( var p = new Process() )
{
p.StartInfo = info;
p.EnableRaisingEvents = true;
p.OutputDataReceived += (s,o) => {
Console.WriteLine(o.Data);
};
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
}
}
I.e. I'm subscribing to the OutputDataReceived event and calling BeginOutputReadLine method. See also this similar Stack Overflow question.
(The method checkSplitFileName in my above source code can be found here)
I had this same problem running my Python script from C#. The problem is that Python buffers the output from stdout (print()).
You could do one of two things here.
1.
Add the following to your Python script, after every print() line to flush the output.
import sys
print('Hello World!')
sys.stdout.flush()
2.
Run the Python compiler with the -u command line parameter. This way you don't need to add the above flush line after every print.
...
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "python.exe -u path " + commandline;
...
Python, by default, buffers its output.
The way to go is to pass a "-u" command line argument to python.
so if you want to execute say hello.py, you would do :
python.exe -u hello.py
Heres the C# code that works for me.
Process p = new Process();
string op = "";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "c:\\python27\\python.exe";
StreamReader outputStream = p.StandardOutput;
StreamReader errorStream = p.StandardError;
p.StartInfo.Arguments = #"-u hello.py";
p.Start();
string output = "";
int offset = 0, readBytes = 0;
char[] buffer = new char[512];
do
{
output = outputStream.ReadLine();
if (!string.IsNullOrEmpty(output))
{
txtOutput.AppendText(output);
txtOutput.AppendText(Environment.NewLine);
offset += readBytes;
Application.DoEvents();
}
Thread.Sleep(3);
} while (!p.HasExited);

calling a ruby script in c#

How do make a call to a ruby script and pass some parameters and once the script is finished return the control back to the c# code with the result?
void runScript()
{
using (Process p = new Process())
{
ProcessStartInfo info = new ProcessStartInfo("ruby C:\rubyscript.rb");
info.Arguments = "args"; // set args
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
string output = p.StandardOutput.ReadToEnd();
// process output
}
}
Just to fill smaller gaps I've implemented the same functionallity with ability to access OutputStream asynchronously.
public void RunScript(string script, string arguments, out string errorMessage)
{
errorMessage = string.empty;
using ( Process process = new Process() )
{
process.OutputDataReceived += process_OutputDataReceived;
ProcessStartInfo info = new ProcessStartInfo(script);
info.Arguments = String.Join(" ", arguments);
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo = info;
process.EnableRaisingEvents = true;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
errorMessage = process.StandardError.ReadToEnd();
}
}
private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
using ( AutoResetEvent errorWaitHandle = new AutoResetEvent(false) )
{
if ( !string.IsNullOrEmpty(e.Data) )
{
// Write the output somewhere
}
}
}

Categories

Resources