How can i pass multiple commands same time in this code - c#

I'm trying to run cmd from local folder and wanted to pass multiple commands at the same time Eg: once i'm able to run this command, p.StandardInput.WriteLine("multichain-util create chain34");after executing this i want to pass this command p.StandardInput.WriteLine("multichai-cli chain 34 -daemon")
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.WorkingDirectory = #"D:\multichain-windows-2.0.2";
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.StandardInput.WriteLine("multichain-util create chain34");
p.StandardInput.Flush();
p.StandardInput.Close();
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd());
Console.ReadKey();
}
}

Move all process related stuff into a method. Take in a list of commands as a parameter for that command. And then instead of one p.StandardInput.WriteLine(), iterate through the list of commands and write them all.
static void Main()
{
var commands = new List<string>() { "dir", "mkdir ABC", "dir" };
ExecuteCmd(commands);
Console.ReadLine();
}
static void ExecuteCmd(List<string> commands)
{
Process p = new Process();
p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
foreach (var comm in commands)
p.StandardInput.WriteLine(comm);
p.StandardInput.Flush();
p.StandardInput.Close();
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd());
}

Related

How to start a process in the background and read standard output

I am new to C#, I have to start a very time consuming process from my C# program of course without bearing the loss of ui freeze, also I want to read the output printed by the program in cmd and at last I want a stop button so that I can close the program whenever I want...
Please help..
try:
using System.Diagnostics;
void startProcess()
{
Process p = new Process();
p.StartInfo.FileName = "FileName";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
var output = p.StandardOutput.ReadToEnd();
}
MethodInvoker starter = new MethodInvoker(startProcess);
starter.BeginInvoke(null, null);
for ending the process:
p.close()
Use something like this:
void StartProcess(){
Process p = new Process();
p.StartInfo.FileName = "yourfile.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
var readingThread = new System.Threading.Thread(() => {
while (!p.StandardOutput.EndOfStream){
Console.WriteLine(p.StandartOutput.ReadLine());
System.Threading.Thread.Sleep(1);
}
}
readingThread.Start();
}

WPF C# - get python version by cmd

I've try to taken python version, so i've start a process with cmd and a command "python --version".
I've try this for first:
using (System.Diagnostics.Process p = new System.Diagnostics.Process())
{
p.StartInfo.UseShellExecute = true;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/k C:/Python36/python --version";
p.StartInfo.CreateNoWindow = false;
var retorno = p.Start();
}
and opened a cmd window and returned this:
cmd return
instead of this, i need this result returned to my WPF application, so i try this:
public static string GetPythonVersion()
{
string command = "python --version";
string output = null;
using (System.Diagnostics.Process p = new System.Diagnostics.Process())
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = String.Format(#"/c {0}\{1} ", "C:/Python36/", command);
p.StartInfo.CreateNoWindow = true;
if (p.Start())
output = p.StandardOutput.ReadToEnd();
}
return output;
}
return empty string to me.
however to an example if i using the same code to return "pip list" to my wpf application working well, but in this case to taken the version the string return empty....
Ok, guys.I've discovered what is wrong on the code. Below the correct code:
public static string GetPythonVersion()
{
string command = "python --version";
string output = null;
using (System.Diagnostics.Process p = new System.Diagnostics.Process())
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = String.Format(#"/c {0}\{1} ", "C:/Python36/", command);
p.StartInfo.CreateNoWindow = true;
if (p.Start())
output = p.StandardError.ReadToEnd();
}
return output;
}
yeah, the python version is on StandardError, because, as you can see on :
https://docs.python.org/3/using/cmdline.html#generic-options
"Print the Python version number and exit."
So when run the command on cmd, at the StandardOutput there is nothin...
thanks to everyone for trying to help me ! now this case is over!

"Multi-Step" commands while using CMD.exe in C#

I'm trying to use "multi-step" command in a c# script, for example the command "net user usrname *" contains 3 steps to enter a password and then validate, i don't know if it is possible to send extra arguments while the Process is running
My code:
Process p = new Process();
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C " + command;
p.StartInfo.WorkingDirectory = startupFolder;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.Start();
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
You would concatenate each command with "&". For example, "cmd /k echo Test 1 & echo test 2".
Edit:
I created a remote control/remote admin solution a while back that uses this same technique to allow you to run batch and PowerShell scripts against remote computers via the web portal. As shown in the below screenshot, it works.
The C# that executes the command can be found here: https://github.com/Jay-Rad/InstaTech_Client/blob/master/InstaTech_Service/Socket.cs#L614
if (cmdProcess == null || cmdProcess.HasExited)
{
var psi2 = new ProcessStartInfo("cmd.exe", "/k " + command);
psi2.RedirectStandardOutput = true;
psi2.RedirectStandardInput = true;
psi2.RedirectStandardError = true;
psi2.UseShellExecute = false;
psi2.WorkingDirectory = Path.GetPathRoot(Environment.SystemDirectory);
cmdProcess = new Process();
cmdProcess.StartInfo = psi2;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.OutputDataReceived += async (object sender, DataReceivedEventArgs args) =>
{
jsonMessage.Status = "ok";
jsonMessage.Output = args.Data;
await SocketSend(jsonMessage);
};
cmdProcess.ErrorDataReceived += async (object sender, DataReceivedEventArgs args) =>
{
jsonMessage.Status = "ok";
jsonMessage.Output = args.Data;
await SocketSend(jsonMessage);
};
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
}
else
{
cmdProcess.StandardInput.WriteLine(command);
}

How to auto fill cmd prompt

I Have a C# program; when I hit a button I want it to open a CMD window, then automatically type in the cmd window and run that said command. So far I have this from 4 hours of research. But nothing is working.
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
//p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("ipconfig");
Any idea on how to fill in a certain text then automatically run it when the button is hit?
With StandardInput and StandardOutput redirected, you cannot see the new window opened. If you want to create a new cmd window and run ipconfig in it, you could do this:
var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c ipconfig & pause";
p.Start();
I agree that if all you want to do is execute "ipconfig" you could just invoke it instead of cmd.exe. Assuming you want to do other things with cmd.exe, here is an example of how to invoke it, have it execute a command, and then terminate (using the /K switch instead of /C will keep cmd.exe running):
using System;
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C ipconfig";
p.Start();
var output = p.StandardOutput.ReadToEnd();
Console.Write(output);
Console.ReadKey();
}
}
}

C# Multiple Input and Output to a Single CMD Process

Hi how do i enter a command to a cmd process which is already started by my application and also to redirect the output back. After that i want to enter my input again.
static void Main(string[] args)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.CreateNoWindow = false;
psi.FileName = "cmd.exe";
psi.Arguments = "/k";
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
Process p = new Process();
p.StartInfo = psi;
p.Start();
while(true)
{
p.StandardInput.WriteLine(Console.ReadLine());
Console.WriteLine(p.StandardOutput.ReadToEnd());
}
Console.Read();
}

Categories