I need get an enter command for my C# process.
my C# code work for test batch file, not for the fortran console application
I read this post: C# Process Call, Interact with Standard Input and Standard Output
but it does not work for me.
Anyone can give me some tips?
my sample batch file (test.bat):
note: this batch file simulate my another application.
#echo off
cls
dir
echo "please input enter key"
pause
tree
my C# code:
private Process _process = null;
private bool _bEnterCR = false;
private void Begin_Click(object sender, RoutedEventArgs e)
{
this.tbOutput.Text = "";
_bEnterCR = false;
if (null != _process)
{
_process.Dispose();
}
string strPathName = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// Use ProcessStartInfo class
_process = new Process();
_process.StartInfo.CreateNoWindow = true;
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_process.StartInfo.FileName = strPathName + "\\test.bat";
_process.StartInfo.WorkingDirectory = strPathName + "\\Output\\";
_process.StartInfo.RedirectStandardError = true;
_process.StartInfo.RedirectStandardInput = true;
_process.StartInfo.RedirectStandardOutput = true;
//_process.EnableRaisingEvents = true;
_process.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
_process.ErrorDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
//_process.Exited += new EventHandler(OnProcessExited);
_process.Start();
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
}
private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (String.IsNullOrEmpty(e.Data) == false)
{
if (e.Data.Contains("please input enter key") && _bEnterCR == false)
{
Debug.WriteLine("Pause Found, Entering <CR> command");
// work for batch file, not for console application
_process.StandardInput.Write(#"\r\n");
_bEnterCR = true;
}
new Thread(() =>
{
this.Dispatcher.Invoke(new Action(() =>
{
tbOutput.AppendText(e.Data + Environment.NewLine);
}));
}).Start();
}
}
Related
I have an app which starts another app. This other app prints a few lines into the Console but noone needs this output and it prints it's output betwenn my own. How can I prevent this other app from printing it's stuff into my console?
I tried to run with ProcessStartInfo.UseShellExecutive both on true and false, also tried to change the console output into a MemoryStream before starting but since I need the Console i had to change the output back and it looks like the other app got their input changed back too.
Process serverprocess = new Process();
serverprocess.StartInfo.FileName = Path.GetFileName(serverpath);
serverprocess.StartInfo.Arguments = launch;
serverprocess.StartInfo.UseShellExecute = false;
serverprocess.StartInfo.RedirectStandardOutput = true;
serverprocess.Start();
In your code ensure that you are re-directing both StandardOutput and StandardError that way everything that the "ThirdPartyApp" writes will be captured in either of these streams.
I have written a small Helper Class that helps with this
You can use like
//Launching excel.exe with /safe as arg
var excelExample1 = #"""C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE"" /safe";
LaunchCMD.Invoke(excelExample1);
//To get its output, if any
var getOutput = LaunchCMD.Output;
LaunchCMD Helper Class
class LaunchCMD
{
public static string Output
{
get; set;
} = "";
public static void Invoke(string command, bool waitTillExit = false, bool closeOutputWindow = false)
{
ProcessStartInfo ProcessInfo;
Process Process = new Process();
ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + command);
ProcessInfo.CreateNoWindow = false;
ProcessInfo.UseShellExecute = false;
ProcessInfo.RedirectStandardOutput = true;
ProcessInfo.RedirectStandardError = true;
Process.EnableRaisingEvents = true;
Process = Process.Start(ProcessInfo);
Process.ErrorDataReceived += ConsoleDataReceived;
Process.OutputDataReceived += ConsoleDataReceived;
Process.BeginOutputReadLine();
Process.BeginErrorReadLine();
if (waitTillExit == true)
{
Process.WaitForExit();
}
if (closeOutputWindow == true)
{
Process.CloseMainWindow();
}
Process.Close();
System.Threading.Thread.Sleep(1000);
Output.ToString();
}
private static void ConsoleDataReceived(object sender, DataReceivedEventArgs e)
{
System.Threading.Thread.Sleep(1000);
if (e.Data != null)
{
Output = Output + e.Data;
}
}
}
I am working on a C# Form tool that will help me convert all of my phone and DSLR video to HEVC, currently, i have a program that uploads the photos and videos to different directories in my home server each time i connect to the WiFi. Once a month or so, i manually convert all the videos, but thought I would automate the process.. I have the Form working perfectly for processing 1 file. but get into trouble when processing a Directory (with possible sub-directories) all at once..
Sorry, this is long, just want to be thorough. here is the button calls
private void processFile_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.InitialDirectory = baseMediaDirectory;
if (file.ShowDialog() == DialogResult.OK)
{
ProcessSinlgeFile(file.FileName);
}
}
(above)for one file and (below) for a directory
private void processDirectory_Click(object sender, EventArgs e)
{
FolderBrowserDialog file = new FolderBrowserDialog();
file.SelectedPath = baseMediaDirectory;
if(file.ShowDialog() == DialogResult.OK)
{
ProcessDirectoryOfFiles(file.SelectedPath);
}
}
private void ProcessDirectoryOfFiles(string selectedPath)
{
List<string> listOfFiles = GetAllFiles(selectedPath);
foreach (string s in listOfFiles)
{
ProcessSinlgeFile(s);
}
}
both ultimately call this method, to do some checks and setup
private void ProcessSinlgeFile(string fileName)
{
if (IsAcceptableMediaFile(fileName))
{
outputWindow.AppendText("File to Process: " + fileName);
processMediaFile =
new MediaFileWrapper(this.outputWindow, new MediaFile(fileName), new NReco.VideoInfo.FFProbe());
if (processMediaFile.OkToProcess)
{
int initialCRFValue = 15;
//ultrafast superfast veryfast faster fast medium slow slower veryslow placebo
string intialSpeed = "veryfast";
try {
ConvertToMPEG(processMediaFile.getFFMPEGCommand(initialCRFValue, intialSpeed), processMediaFile);
}
catch
{
// at somepoint, we'll catch a bad file size (or compression)
// then change the CRF value and/or compression speed
}
}
}
}
ultimately I get to this Method and run into trouble.
private async void ConvertToMPEG(string arguments, MediaFileWrapper processMediaFile)
{
startTime = DateTime.Now;
watch = new Stopwatch();
watch.Start();
progressBar1.Minimum = 0;
progressBar1.Maximum = processMediaFile.GetTotalMilliseconds();
// Start the child process.
p = new Process();
//Setup filename and arguments
outputWindow.AppendText("ffmpeg " + arguments);
p.StartInfo.Arguments = arguments;
p.StartInfo.FileName = "ffmpeg.exe";
p.StartInfo.UseShellExecute = false;
// Redirect the output stream of the child process.
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
// capture the date for stdout and std error
// note FFMPEG uses Stderr exclusively
p.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataReceived);
p.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceived);
// Hide Console Window
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
await p.WaitForExitAsync();
}
and WaitForExitAsync is in another class because in can not be in here with a Form
public static Task WaitForExitAsync(this Process process,
CancellationToken cancellationToken = default(CancellationToken))
{
var tcs = new TaskCompletionSource<object>();
process.EnableRaisingEvents = true;
process.Exited += (sender, args) => tcs.TrySetResult(null);
if (cancellationToken != default(CancellationToken))
cancellationToken.Register(tcs.SetCanceled);
return tcs.Task;
}
however, single files work fine, when I call a directory through, it continuously starts processes for each file, trying to run them all at the same time. You can see I tried implementing this
process.WaitForExit() asynchronously
with no luck.
I've got a problem with showing results of cmd commands to richtextbox.
So far, I have this code:
private void richTextBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
e.SuppressKeyPress = true;
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = #"C:\Windows\System32\cmd.exe";
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine(richTextBox2.Text);
cmdProcess.StandardInput.WriteLine("exit");
cmdProcess.WaitForExit();
richTextBox1.Text = richTextBox1.Text + cmd_DataReceived + Environment.NewLine;
}
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output from other process");
Console.WriteLine(e.Data);
}
I've tried replacing "Console.WriteLine(e.Data);" with "richTextBox1.Text = richTextBox1.Text + (e.Data);" but it wouldn't be accepted.
I also tried "richTextBox1.Text = richTextBox1.Text + cmd_DataReceived";
But that didn't work iether.
Then I tried replacing console.writeline with messagebox.show(e.data) but again.. nope
The commands work, but it won't display
I know I copied most of the code, and it's probably meant for a console application.
Please help
As you're waiting for the process to exit with cmdProcess.WaitForExit, cmd_DataReceived is getting all the data. This means you're going to need to store the data you get from the callback, and after WaitForExit ends, you can then set the text box with the contents of the stored data.
One simple way is to use a StringBuilder:
// Have a reference to a stringbuilder that both functions can see
StringBuilder m_output;
private void richTextBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Before the process starts, create a new stringbuilder
m_output = new StringBuilder();
e.Handled = true;
e.SuppressKeyPress = true;
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = #"C:\Windows\System32\cmd.exe";
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine(richTextBox2.Text);
cmdProcess.StandardInput.WriteLine("exit");
cmdProcess.WaitForExit();
// And now that everything's done, just set the text
// to whatever's in the stringbuilder
richTextBox1.Text = m_output.ToString();
// We're done with the stringbuilder, let the garbage
// collector free it
m_output = null;
}
}
// Note: This is no longer a static method so it has
// access to the member variables, including m_output
void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
Debug.WriteLine("Output from other process");
Debug.WriteLine(e.Data);
// Add the data, one line at a time, to the string builder
m_output.AppendLine(e.Data);
}
I want to perform some command lines to display the result after each input.
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("ftp");
//output
sw.WriteLine("open ftp.server.com");
//output
sw.WriteLine("username");
//output
sw.WriteLine("password");
//output
}
}
Help me to understand how to make the output result after each sw.WriteLine(...)?
Updated
It is not working with ftp. Why?
Initialization:
Test test = new Test();
test.start();
Console.ReadKey();
Class Test:
class Test
{
static StringBuilder StdOutput = new StringBuilder();
Process p = null;
Queue<string> cmdQueue = new Queue<string>();
public void start(){
cmdQueue = new Queue<string>();
cmdQueue.Enqueue("cd c:\\");
cmdQueue.Enqueue("dir");
cmdQueue.Enqueue("ftp");
cmdQueue.Enqueue("open us1.hostedftp.com");
cmdQueue.Enqueue("z3r9#ya.ru");
cmdQueue.Enqueue("123456");
cmdQueue.Enqueue("dir");
setupProcess();
startProcess();
}
private void setupProcess()
{
p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd";
info.CreateNoWindow = true;
info.RedirectStandardOutput = true;
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.OutputDataReceived += new DataReceivedEventHandler(OutputDataHandler);
StdOutput = new StringBuilder();
p.StartInfo = info;
}
private async void startProcess()
{
p.Start();
p.BeginOutputReadLine();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
while (cmdQueue.Count > 0)
{
string cmd = cmdQueue.Dequeue();
if (cmd != null & cmd != "")
{
await sw.WriteLineAsync(cmd);
Thread.Sleep(100);
//System.Console.WriteLine(StdOutput);
}
else
{
break;
}
}
Console.WriteLine(StdOutput);
}
p.WaitForExit();
}
}
private static void OutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
StdOutput.Append(Environment.NewLine + outLine.Data);
//System.Console.WriteLine(Environment.NewLine + outLine.Data);
}
}
}
I assume that you are actually asking about how to catch outputs from all the commands you want to have executed in the (one) process.
Here is a version of a solution I came up with a long time ago, when I was a rookie here..
The trick is to collect the output as is comes along by listening to events the Process will trigger whenever output gets created: OutputDataReceived and ErrorDataReceived. We need to run things async for this to work, so it will look a little more complicated than the usual examples, which only have one process executing one command..:
First a few variables:
Queue<string> cmdQueue = new Queue<string>();
static StringBuilder StdOutput = new StringBuilder();
static StringBuilder ErrOutput = new StringBuilder();
Process p = null;
Task processTask = null;
bool processIsRunning = false;
Here is a button click event that starts processing all commands from a multiline TextBox. Output gets collected in the two StringBuilders; when the queue is empty, I wait a little longer..:
private void button1_Click(object sender, EventArgs e)
{
cmdQueue = new Queue<string>(tb_commands.Lines.ToList());
setupProcess();
startProcessTask();
while (cmdQueue.Count > 0) Thread.Sleep(100);
Thread.Sleep(500);
tb_out.AppendText(StdOutput + "\r\n" + ErrOutput + "\r\n");
}
Here is the routine that set up the Process. Here we register two events that will notify us when there are lines in the output streams..:
private void setupProcess()
{
p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.CreateNoWindow = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.OutputDataReceived += new DataReceivedEventHandler(OutputDataHandler);
p.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataHandler);
StdOutput = new StringBuilder();
ErrOutput = new StringBuilder();
p.StartInfo = info;
}
After the setup we can start a Task that will start our Process asynchonously..:
private void startProcessTask()
{
var task = Task.Factory.StartNew(() => startProcess());
processTask = task;
}
..and finally here is the async method that after starting the Process and beginning with the asynchronous read operations on the redirected streams, keeps feeding it all lines from the command queue.
private async void startProcess()
{
try { p.Start(); processIsRunning = true; } catch
{
ErrOutput.Append("\r\nError starting cmd process.");
processIsRunning = false;
}
p.BeginOutputReadLine();
p.BeginErrorReadLine();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
do
{
try
{
string cmd = cmdQueue.Dequeue();
if (cmd != null & cmd != "") await sw.WriteLineAsync(cmd);
} catch { }
} while (processIsRunning);
try { p.WaitForExit(); } catch { ErrOutput.Append("WaitForExit Error.\r\n"); }
}
}
The last pieces are the two events we have registered for reading the output from the two streams and adding them to the StringBuilders:
private static void OutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
StdOutput.Append(Environment.NewLine + outLine.Data);
}
}
private static void ErrorDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
ErrOutput.Append(Environment.NewLine + outLine.Data);
}
}
Note that this works fine for all sorts of commands you can feed into the process, including FTP. Here I change my codepage, show the images I have before, log in to an FTP server, call up the help page, cd and dir, download an image, close the connection and check the images I have now..:
One Caveat: There must be something wrong in the way I wrote this, as VS keeps complaining about a System.InvalidOperationException and the exe file hogs ~10% cpu. Helping me out would be very much appreciated..
I need to run PLink as a process as part of WinForm application
this is my code
public void RunProcess(string FileName, string Arguments, bool EventWhenExit , bool IsWaitBeforeStart = true )
{
process = new Process();
process.OutputDataReceived += new DataReceivedEventHandler(OnDataReceivedEvent);//**
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = FileName; // Gets or sets the application or document to start.
process.StartInfo.Arguments = Arguments;//Gets or sets the set of command-line arguments to use when starting the application
if (IsWaitBeforeStart) Thread.Sleep(5000);
if (EventWhenExit)
{
process.EnableRaisingEvents = true;
process.Exited += new EventHandler(myprocess_Exited);
}
process.Start();
process.BeginOutputReadLine();
PID = process.Id;
ProcessTimeOut.Enabled = true;
ProcessInputStream = process.StandardInput;
ProcessTimeOut.Enabled = false;
}
private void OnDataReceivedEvent(object sender, DataReceivedEventArgs e)
{
//prints to screen using control.invoke
//add data to a string list
}
My setup consist of a telnet server that I need to run few command on it and parse the result
if I run the application from cmd it prints the result under one sec (it is about 50 rows)
but if I run it using my code it takes up to almost 7 sec !
From my understanding process.start() and running via cmd should be the same
so the problem should be somewhere in my code or logic
what can be the problem ?
Ok so with help from Vajura comment I've made a simple(vary) buffer to implement simple consumer/producer pattern
inside RunProcess :
public void RunProcess(string FileName, string Arguments, bool EventWhenExit , bool IsWaitBeforeStart = true )
{
//... same code as before
PollingService();
}
second changing the event DataReceivedEventHandler
to store data to buffer (and stop invoking the print to UI)
the code is something like ProcessLog.Add(e.Data);
now for the second Thread to run over the buffer :
private void PollingService()
{
var T = new Thread (()=>
{
while (true)
{
if (ProcessLogIndex < ProcessLog.Count)
{
lock (this)
{
var tempList = ProcessLog.GetRange(ProcessLogIndex, ProcessLog.Count - ProcessLogIndex);
ProcessLogIndex = ProcessLog.Count;
foreach (var cell in tempList)
{
string ToSend = !string.IsNullOrEmpty(cell) ? (cell.Contains('$') ? cell.Substring(cell.LastIndexOf('$')) : cell) : "";
onDataOutputFromProcess(this, ToSend, Proc.ToString());
}
}
}
Thread.Sleep(1000);
}
});
T.IsBackground = true;
T.Start();
}