How do I execute command in c#? - c#

I want to execute command to call microphone config.
control mmsys.cpl,,1
I try following code but I throw Win32Exception, The system cannot find the file specified.
Process.Start("control mmsys.cpl,,1");

It should be:
Process.Start("control","mmsys.cpl,,1")
Documentation: http://msdn.microsoft.com/en-us/library/h6ak8zt5.aspx

You can try this -
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
/* execute "dir" command */
cmd.StandardInput.WriteLine("dir");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.Close();
You can write your command to a bat file and execute it from the command prompt using the above method.

Related

Executing netstat from C# app returns "File Not Found" error

I am trying to execute netstat command from my C# code and get "File Not Found" error.
Do I have to specify where "netstat.exe" is?
If so, how would I do it if (hypothetically) netstat and findstr are in two different folders?
Process cmd = new Process();
cmd.StartInfo.FileName = "netstat -a | findstr 5840";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
try
{
cmd.Start();
}
catch (System.ComponentModel.Win32Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
StreamReader reader = cmd.StandardOutput;
string output = reader.ReadToEnd();
Console.WriteLine(output);
This is what fixed the problem:
// create the ProcessStartInfo using "cmd" as the program to be run and "/c " as the parameters.
// /c tells cmd that we want it to execute the command that follows and then exit.
string command = "netstat -a | findstr " + sTCPPort;
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
result = proc.StandardOutput.ReadToEnd();
Without seeing the exact it is hard to know the exact issue, but it looks like you may need to cmd.exe and pass your command to it as an argument.

How to run a bash command from Mono/MonoDevelop in Red Hat Linux?

I want to run the following bash command using C# and MonoDevelop and store the output to a variable.
./TestApp --H
My MonoDevelop Code:
Process proc = new Process();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "/usr/mono/TestApp --H";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardErrort = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
var output = proc.RedirectStandardOutput.ReadToEnd()
The above code is not working. The output variable is not getting the value as expected.
If I modify the above code by using a shell script, then its working.
Test.sh
#!/bin/bash
/usr/mono/TestApp --H;
Modified Mono Code:
proc.StartInfo.Arguments = "Test.sh";
Thank You
If /usr/mono/TestApp is not a shell script (for your question I guess it is not) this should work (you do not need bash to run programs):
Process proc = new Process();
proc.StartInfo.FileName = "/usr/mono/TestApp";
proc.StartInfo.Arguments = "--H";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
var output = proc.StandardOutput.ReadToEnd ();
Console.WriteLine("stdout: {0}", output);
By the way, be careful when using redirects. If pipes between TestApp process and Mono process get full, your application will not be able to finish (there is deadlock) Read the documentation for further information: RedirectStandardOutput

Windows Form Write to Console

I am simply trying to open the console and write a single line and execute it with the console staying open once the line is written. Currently, the command line is opening blank and not writing anything. Any way to fix this?
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = false;
cmd.Start();
cmd.StandardInput.WriteLine("echo hello");
cmd.StandardInput.WriteLine("pause");
cmd.WaitForExit();
This will fix it:
cmd.StartInfo.RedirectStandardOutput = false;
This works perfect for me:
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardInput = true;
//cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
cmd.StandardInput.WriteLine("pause");
System.Threading.Thread.Sleep(5000);
cmd.StandardInput.WriteLine(" ");
cmd.StandardInput.WriteLine("dir /p");
cmd.StandardInput.WriteLine("exit");
cmd.WaitForExit();
}
}
}
You could most likely just issue a pause:
cmd.StandardInput.WriteLine("pause");
Should solve it.
Remember to add:
cmd.StartInfo.RedirectStandardInput = false;
If that does not work then most likely still an issue, as reported at Microsoft regarding CMD specifically and output. See: http://connect.microsoft.com/VisualStudio/feedback/details/609801/unable-to-redirect-only-the-standard-input-of-process-cmd-exe-or-batch-file-from-windows-form-application
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = "/K \"echo hello\"";
cmd.Start();

windows forms to run commands

I am trying to launch a new cmd process, from that run a batch file to setup environments and from that run custom commands. Is this possible?
So far I have:
Process cmd = new Process();
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Filename = <setup.cmd path>
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.RedirectStandardInput = true;
cmd.Start()
this successfully set up the environment but the cmd window immediately closes and i can't submit more commands.
Simply add the ProcessStartInfo.Arguments and pass "/K" as value
Process cmd = new Process();
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = "/K";
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.RedirectStandardInput = true;
cmd.Start();
Passing the argument /K will force the command window to remain open
You can add also the name of your batch file after the /K
cmd.StartInfo.Arguments = "/K yourbatch.cmd args1 args2";

Write only the output from the console command

I'm trying to build a .net application that will run some console commands (like running phantomJs) and return me the outcome of the operations. But by default I'm getting everything from the starting of cmd.exe to closing it. Any ideas for a quick fix or do I need to play with regexes ?
Here's my code as for now :
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader sOut = proc.StandardOutput;
System.IO.StreamWriter sIn = proc.StandardInput;
sIn.WriteLine("phantomjs -v");
sIn.WriteLine("EXIT");
proc.Close();
string results = sOut.ReadToEnd().Trim();
sIn.Close();
sOut.Close();
PhantomJS is an executable (according to their docs) - why not execute that directly rather than running cmd.exe? That will avoid the cmd.exe noise.
Or redirect the output of phantomjs to a log file and load the log file.
Or if you absolutely have to use cmd.exe and can't redirect ... I'd maybe throw some echo sentinels around the phantomjs to serve as parse start/stop points.
e.g.,
echo PARSE START
runcommand.exe
echo PARSE STOP
But don't do that.
Instead of using the different streams. Why not use cmd as filename and pass it the -c "phantomjs -v" as argument. Then use proc.StandardOutput.ReadToEnd() to grab everything that is outputted in the console. This should leave out unneeded info as it only reads what the output of the executed command is.
Following code might not work, but should give you the general idea.
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd";
psi.Arguments = "/c \"phantomjs -v\"";
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
// Optional other options
Process proc = Process.Start(psi);
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
If you are on an unix machine:
sIn.WriteLine("phantomjs -v > /dev/null");
Windows:
sIn.WriteLine("phantomjs -v > NUL");
I hope that the following would be helpful!
{
Process xyProcess = new Process();
xyProcess.StartInfo.FileName = "FilenameYouWant";
xyProcess.StartInfo.UseShellExecute = false;
xyProcess.StartInfo.CreateNoWindow = true;
xyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
xyProcess.StartInfo.RedirectStandardInput = true;
xyProcess.StartInfo.RedirectStandardOutput = true;
xyProcess.StartInfo.RedirectStandardError = true;
xyProcess.StartInfo.Arguments += "any arg1 you want ";
xyProcess.StartInfo.Arguments += "any arg2 you want ";
xyProcess.EnableRaisingEvents = true;
xyProcess.OutputDataReceived += process_DataReceived;
// Start the process
xyProcess.Start();
xyProcess.BeginErrorReadLine();
xyProcess.BeginOutputReadLine();
xyProcess.WaitForExit();
}
static private void process_DataReceived(object sender, DataReceivedEventArgs e)
{
//Catch the process response here
}

Categories