running dos command line from C#? - c#

I am trying to run this command from command-line prompt:
"D:\\fiji\\fiji.exe -macro D:\\fiji\\macros\\FFTBatch.ijm --headless"
It works perfect when I type it in a command-line console.
However, when I was trying to make it work from C# application, it failed. I tried following, but seems the command above did not get executed somehow:
string fijiCmdText = "D:\\fiji\\fiji.exe -macro D:\\fiji\\macros\\FFTBatch.ijm --headless";
System.Diagnostics.Process.Start("cmd.exe", fijiCmdText);
Anyone has any idea how to change it to work? Thanks.

The problem was solved as in the direction Chris Haas pointed out. It does not mean other answers don't work, it just means the problem can be solved at least in one way.
Here it is, simply adding "/C " in the code, and it should work:
Original that did not work:
string fijiCmdText = "D:\\fiji\\fiji.exe -macro D:\\fiji\\macros\\FFTBatch.ijm --headless";
System.Diagnostics.Process.Start("cmd.exe", fijiCmdText)
;
Current code that works:
string fijiCmdText = "/C D:\\fiji\\fiji.exe -macro D:\\fiji\\macros\\FFTBatch.ijm --headless";
System.Diagnostics.Process.Start("cmd.exe", fijiCmdText);
Here is the reference mentioned by Chris Haas. See EDIT3

You don't have to run cmd.exe, just create ProcessStartInfo object and pass the command with its parameters to it. Like this:
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo("your command", "parameters");
Here is an example that shows you how to do it:
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo("tree.com", "/f /a");
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = info;
p.Start();
p.WaitForExit();
So in your case, this is your command: "D:\\fiji\\fiji.exe" and this is your command parameters or arguments: #"-macro D:\\fiji\\macros\\FFTBatch.ijm --headless"

Try This:
ProcessStartInfo info = new ProcessStartInfo(#"D:\fiji\fiji.exe",#"-macro D:\fiji\macros\FFTBatch.ijm --headless");
Process process = new Process();
process.StartInfo = info;
process.Start();

Related

How to run multiple cmd commands from c# console app

I'm looking to automate nupkg creation in a c# app. I'm aiming to include nuget.exe in my project and use System.Diagnostics to launch cmd.exe as a process and then pass the required commands, which would be 'cd project\path\here', 'nuget spec something.dll' and 'nuget pack something.nuspec'.
The code I have so far is:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo(#"C:\Windows\System32\cmd.exe", #"mkdir testdir");
p.StartInfo = info;
p.Start();
Console.ReadLine();
However, it doesn't even create the testdir, and I've got no idea how to chain those commands. There is a method called WaitForInputIdle on my p Process, but it raises events and I've got no idea how to handle those to be honest.
A perfect solution would also let me read output and input. I've tried using StreamWriter p.StandardInput, but then there's the problem of checking whether a command is finnished and what was the result.
Any help would be much appreciated.
Edit: Success! I've managed to create a directory :)
Here's my code now:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo(#"C:\Windows\System32\cmd.exe");
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
sw.WriteLine("mkdir lulz");
}
Still no idea how to await for input and follow up with more commands, though.
You can do this by three ways
1- The easiest option is to combine the two commands with the '&' symbol.
var processInfo = new ProcessStartInfo("cmd.exe", #"command1 & command2");
2- Set the working directory of the process through ProcessStartInfo.
var processInfo = new ProcessStartInfo("cmd.exe", #"your commands here ");
processInfo.UseShellExecute = false;
processInfo.WorkingDirectory = path;
3- Redirecting the input and output of the process. (Also done through the ProcessStartInfo).This is required when you like to send more input to the process, or when you want to get the output of the process
Also see this answer

How to pass arguments to an already open terminal via System.Diagnostics.Process()

I have been messing around with triggering a bash script via C#. This all works fine when I first call the "open" command with arguments which in turn opens my .command script via Terminal.
Once the "open" command is used once Terminal or iTerm will remain open in the background, at which point calling the "open" command with arguments then has no further effect. I sadly have to manually quit the application to trigger my script again.
How can I pass arguments to an already open terminal application to restart my script without quitting?
I've searched online ad can't seem to work it out, it already took a good amount of time solve the opening code. Your help is much appreciated.
Here is the C# code I'm using to start the process:
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "open";
p.StartInfo.WorkingDirectory = installFolder;
p.StartInfo.Arguments = "/bin/bash --args \"open \"SomePath/Commands/myscript.command\"\"";
p.Start();
Thanks
EDIT:
Both answers were correct, this might help others:
ProcessStartInfo startInfo = new ProcessStartInfo("/bin/bash");
startInfo.WorkingDirectory = installFolder;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine("echo helloworld");
process.StandardInput.WriteLine("exit"); // if no exit then WaitForExit will lockup your program
process.StandardInput.Flush();
string line = process.StandardOutput.ReadLine();
while (line != null)
{
Debug.Log("line:" + line);
line = process.StandardOutput.ReadLine();
}
process.WaitForExit();
//process.Kill(); // already killed my console told me with an error
You can try:
before calling p.Start():
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
// for the process to take commands from you, not from the keyboard
and after:
if (p != null)
{
p.StandardInput.WriteLine("echo helloworld");
p.StandardInput.WriteLine("executable.exe arg1 arg2");
}
(taken from here)
This is what you may be looking for :
Gets a stream used to write the input of the application.
MSDN | Process.StandardInput Property
// This could do the trick
process.StandardInput.WriteLine("..");

sending command to cmd through c#

I want to execute a command to lock the drive through bit locker when button is clicked. How to do this? I'm new in c#
The command is:
manage-bde -lock x:
How it will be send to console? here is the code
private void btnlock_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 manage-bde -lock "+textBox1.Text+":";
process.StartInfo = startInfo;
process.Start();
}
You can use the Process class in System.Diagnostics namespace.
It should be something like this:
System.Diagnostics.Process.Start("manage-bde", "-lock x:");
The command isn't being executed because your command line doesn't know where to find the manage-bde program.
All you need to do is add the full path of the file like so:
startInfo.Arguments = #"/C C:\Program Files\Foo\manage-bde.exe -lock "+textBox1.Text+":";
Note: I'm not sure if the .exe part is necessary, but it doesn't hurt adding it in. Also, make sure you either use 2 backslashes (\\) or use the # before the quotation mark at the start.

Process.Start() fails to open the exe

I'm trying to launch an application from c# code. Below is the code.. But the exe gives the error "Application has encountered a problem and needs to close. Sorry for the inconvenience".
I'm passing the command values as
command = "\"C:\\Program Files\\Nimbuzz\\Nimbuzz.exe\"";
code:
private int ExecuteSystemCommand(string command)
{
procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
return proc.Id;
}
But the exe opens normally when opened from the desktop short cut. I dont know whats wrong. Please suggest.
You must specify the EXE you want to execute.
Process.Start("cmd.exe", ...)
It would appear that these articles answer the question:
ProcessStartInfo.UseShellExecute
ProcessStartInfo.FileName
Well I just found out that, I need to set the Working directory first before calling the Process.Start()
Directory.SetCurrentDirectory("C:\\Program Files\\Nimbuzz\\");

Running cmd commands via .NET?

System.Diagnostics.Process proc0 = new System.Diagnostics.Process();
proc0.StartInfo.FileName = "cmd";
proc0.StartInfo.WorkingDirectory = Path.Combine(curpath, "snd");
proc0.StartInfo.Arguments = omgwut;
And now for some background...
string curpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
omgwut is something like this:
copy /b a.wav + b.wav + ... + y.wav + z.wav output.wav
And nothing happens at all. So obviously something's wrong. I also tried "copy" as the executable, but that doesn't work.
Try the prefixing your arguments to cmd with /C, effectively saying cmd /C copy /b t.wav ...
According to cmd.exe /? using
/C <command>
Carries out the command specified by
string and then terminates
For your code, it might look something like
// ..
proc0.StartInfo.Arguments = "/C " + omgwut;
Notes:
A good way to test whether your command is going to work is to actually try it from a command prompt. If you try to do cmd.exe copy ... you'll see that the copy doesn't occur.
There are limits to the length of the arguments you can pass as arguments. From MSDN: "The maximum string length is 2,003 characters in .NET Framework applications and 488 characters in .NET Compact Framework applications."
You can bypass the shelling out to command by using the System.IO classes to open the files and manually concatenate them.
Try this it might help you.. Its working with my code.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.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
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
}
Even you can try this.. this is even better.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments="http://www.microsoft.com";
proc.Start();
proc.WaitForExit();
MessageBox.Show("You have just visited " + proc.StartInfo.Arguments);
Daniels cmd /c idea will work. Keep in mind there is a limit to the length of a command line probably 8k in your case see this for details.
Since you are in a .Net app anyway, File.Copy may be quite a bit easier/cleaner than this approach.

Categories