Running Command Line from C# without Window and Getting Output [duplicate] - c#

This question already has answers here:
How To: Execute command line in C#, get STD OUT results
(18 answers)
Closed 7 years ago.
I am trying to run a command line script from C#. I want it to run without a shell and place the output into my string output. It doesn't like the p.StartInfo line. What am I doing wrong? I am not running a file like p.StartInfo.FileName = "YOURBATCHFILE.bat" like How To: Execute command line in C#, get STD OUT results. I need to set the "CMD.exe" and command line string. I have tried p.Start("CMD.exe", strCmdText); but that gives me the error: "Memer 'System.Diagnostics.Process.Start(string,string)' cannot be accessed with an instance reference; qualify it with a type name instead."
string ipAddress;
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
string strCmdText;
strCmdText = "tracert -d " + ipAdress;
p.StartInfo("CMD.exe", strCmdText);
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

This code gives me the correct ouput.
const string ipAddress = "127.0.0.1";
Process process = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
FileName = "cmd.exe",
Arguments = "/C tracert -d " + ipAddress
}
};
process.Start();
process.WaitForExit();
if(process.HasExited)
{
string output = process.StandardOutput.ReadToEnd();
}

You are using StartInfo incorrectly. Have a look at documentation for ProcessStartInfo Class and Process.Start Method (). Your code should look something like this:
string ipAddress;
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
string strCmdText;
strCmdText = "/C tracert -d " + ipAdress;
// Correct way to launch a process with arguments
p.StartInfo.FileName="CMD.exe";
p.StartInfo.Arguments=strCmdText;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Also, note that I added /C argument to strCmdText. As per cmd /? help:
/C Carries out the command specified by string and then terminates.

Related

How to open Ubuntu's bash.exe shell using C# on Windows?

as described in the title, I wanna open up the ubuntu-shell on my windows pc, passing a
"cd /mnt/c/users/xyz/desktop" to it then passing a
"python3 some_script.py arg1, arg2" to it
all this works wonderful if done manually via mouseclicks but from code (see below:)
it doesnt write anything to the console which opens.
string ExecuteCommand(string command)
{
// Execute wsl command:
var StartInfo = new ProcessStartInfo
{
FileName = #"bash.exe",
WorkingDirectory = #"C:\Windows\System32",
//Arguments = "/c " + "root#DESKTOP-OUTEVME:~#",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Normal,
};
using (var process = Process.Start(StartInfo))
{
process.StandardInput.WriteLine();
process.EnableRaisingEvents = true;
process.OutputDataReceived += (s, e) => MessageBox.Show(e.Data);
process.BeginOutputReadLine();
process.StandardInput.WriteLine(command);
process.StandardInput.WriteLine("exit");
process.WaitForExit();
//result = process.StandardOutput.ReadToEndAsync().Result;
}
return result;
}
return ExecuteCommand(#"wsl cd /mnt/c/users/shho3/desktop");
Anyone maybe an idea what I could do wrong?
Much thanks!
You could pass everything in the command line instead of piping into the process. I think it would save you a lot of trouble. Try bash.exe -c "cd /mnt/c/Users/shho3/Desktop; python some_script.py arg1 arg2":
Process.Start("bash.exe", "-c \"cd /mnt/c/Users/shho3/Desktop; python some_script.py arg1 arg2\"").WaitForExit()
Alternatively you can also just set the working directory to C:\Users\shho3\Desktop (instead of C:\Windows\System32) and call bash.exe -c "python some_script.py arg1 arg2", then you don't even have to convert the path:
Process.Start(new ProcessStartInfo("bash.exe", "-c \"python some_script.py arg1 arg2\"") {
WorkingDirectory = "C:\\Users\\ssho3\\Desktop"
}).WaitForExit()

How do I check if a command prompt command executes valid? [duplicate]

This question already has answers here:
How To: Execute command line in C#, get STD OUT results
(18 answers)
Closed 1 year ago.
So I want to check if node.js is installed using c# by using this code.
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 node -v";
process.StartInfo = startInfo;
process.Start();
I'm not sure how to check if the command ran successfully. Is it possible in c# and if it is how?
Set StartInfo appropiately and redirects the standard output.
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/C node -v",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
// Starts the process and reads its output.
proc.Start();
string output = proc.StandardOutput.ReadToEnd();

Run Bash Commands from Mono C#

I am trying to make a directory using this code to see if the code is executing but for some reason it executes with no error but the directory is never made. Is there and error in my code somewhere?
var startInfo = new
var startinfo = new ProcessStartInfo();
startinfo.WorkingDirectory = "/home";
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
Console.WriteLine ("Shell has been executed!");
Console.ReadLine();
This works best for me because now I do not have to worry about escaping quotes etc...
using System;
using System.Diagnostics;
class HelloWorld
{
static void Main()
{
// lets say we want to run this command:
// t=$(echo 'this is a test'); echo "$t" | grep -o 'is a'
var output = ExecuteBashCommand("t=$(echo 'this is a test'); echo \"$t\" | grep -o 'is a'");
// output the result
Console.WriteLine(output);
}
static string ExecuteBashCommand(string command)
{
// according to: https://stackoverflow.com/a/15262019/637142
// thans to this we will pass everything as one command
command = command.Replace("\"","\"\"");
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = "-c \""+ command + "\"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
proc.WaitForExit();
return proc.StandardOutput.ReadToEnd();
}
}
This works for me:
Process.Start("/bin/bash", "-c \"echo 'Hello World!'\"");
My guess is that your working directory is not where you expect it to be.
See here for more information on the working directory of Process.Start()
also your command seems wrong, use && to execute multiple commands:
proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
Thirdly you are setting your working directory wrongly:
proc.StartInfo.WorkingDirectory = "/home";

How do I execute a shell script in C#?

I have one file which contains a Unix shell script. So now I wanted to
run the same in .NET. But I am unable to execute the same.
So my point is, is it possible to run the Unix program in .NET? Is there any API like NSTask in Objective-C for running Unix shell scripts so any similar API in .NET?
It has been answered before. Just check this out.
By the way, you can use:
Process proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = "program.exe",
Arguments = "command line arguments to your executable",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
After that start the process and read from it:
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
string line = proc.StandardOutput.ReadLine();
// Do something with line
}
ProcessStartInfo frCreationInf = new ProcessStartInfo();
frCreationInf.FileName = #"C:\Program Files\Git\git-bash.exe";
frCreationInf.Arguments = "Test.sh";
frCreationInf.UseShellExecute = false;
var process = new Process();
process.StartInfo = frCreationInf;
process.Start();
process.WaitForExit();

c# run command not executing the command

I want to run this:
string command = "echo test > test.txt";
System.Diagnostics.Process.Start("cmd.exe", command);
It's not working, what am I doing wrong?
You are missing to pass the /C switch to cmd.exe to indicate that you want to execute a command. Also notice that the command is put in double quotes:
string command = "/C \"echo test > test.txt\"";
System.Diagnostics.Process.Start("cmd.exe", command).WaitForExit();
And if you don't want to see the shell window you could use the following:
string command = "/C \"echo test > test.txt\"";
var psi = new ProcessStartInfo("cmd.exe")
{
Arguments = command,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = Process.Start(psi))
{
process.WaitForExit();
}
This should sort of get you started:
//create your command
string cmd = string.Format(#"/c echo Hello World > mydata.txt");
//prepare how you want to execute cmd.exe
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
psi.Arguments = cmd;//<<pass in your command
//this will make echo's and any outputs accessiblen on the output stream
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process p = Process.Start(psi);
//read the output our command generated
string result = p.StandardOutput.ReadToEnd();

Categories

Resources