If I run following command in console, it will succeed:
"C:\Users\myAccount.Unit\Favorites\Downloads\fiji.app (1)\fiji.exe" -macro "C:\Users\myAccount.Unit\Favorites\Downloads\fiji.app (1)\macros\FFTBatch.ijm" C:\Users\myAccount.Unit\Documents\Untitled001\
where
"C:\Users\myAccount.Unit\Favorites\Downloads\fiji.app (1)\fiji.exe" is the application file,
"C:\Users\myAccount.Unit\Favorites\Downloads\fiji.app (1)\macros\FFTBatch.ijm" is the macro file that gets executed,
and C:\Users\myAccount.Unit\Documents\Untitled001\ is the images processed by the previous macro.
However, when I use C# to do this job, it failed (meaning no response at all). Following is the relevant code:
string _fijiExeFile = "C:\\Users\\myAccount.Unit\\Favorites\\Downloads\\fiji.app (1)\\fiji.exe";
string _ijmFile = "C:\\Users\\myAccount.Unit\\Favorites\\Downloads\\fiji.app (1)\\macros\\FFTBatch.ijm";
string _inputDir = "C:\\Users\\myAccount.Unit\\Documents\\Untitled001\\";
string fijiCmdText = string.Format("/C \"{0}\" -macro \"{1}\" {2}", _fijiExeFile, _ijmFile, _inputDir);
try
{
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 = fijiCmdText;
process.StartInfo = startInfo;
process.Start();
_processOn = true;
process.WaitForExit();
ret = 1;
}
catch (Exception ex)
{
ret = 0;
}
(The path are actually obtained from the UI, I am just posting what it is.)
This is what I observed for fijiCmdText when I step in:
"/C \"C:\\Users\\myAccount.Unit\\Favorites\\Downloads\\fiji.app (1)\\fiji.exe\" -macro \"C:\\Users\\myAccount.Unit\\Favorites\\Downloads\\fiji.app (1)\\macros\\FFTBatch.ijm\" C:\\Users\\myAccount.Unit\\Documents\\Untitled001\\"
If I only use
string fijiCmdText = string.Format("/C \"{0}\"", _fijiExeFile);
It does launch the .exe application, however if I intended to add the macro file path, it fails.
Any thing wrong here?
The link I posted states that you need to use the /S switch and put the entire command in quotes:
string fijiCmdText = string.Format("/S /C \"\"{0}\" -macro \"{1}\" {2}\"", _fijiExeFile, _ijmFile, _inputDir);
Or, more clearly:
string fijiCmdText = "/S /C \"<command line that can have quotes>\"";
Related
What is wrong with this code to run a command in command prompt? I try to run this code and it does not give any error and it does not do what it is supposed to do. It works fine if I copy the command to command prompt and run it manually?
Thank you!
[TestMethod]
public void TestProcess()
{
string command1 = #"sejda-console simplesplit --files -f C:\TestFiles\test.pdf -o C:\TestFiles\split1\ -s all";
ProcessStartInfo processInfo;
Process process;
//I have the batch file sejda-console in C:\sejda-console-3.2.83\bin so I concatenated the directory of the batch file with the actual command.
processInfo = new ProcessStartInfo("cmd.exe", #"C:\sejda-console-3.2.83\bin " + command1);
processInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process = Process.Start(processInfo);
process.WaitForExit();
process.Close();
}
Alternatively, I am trying this one too which does not work either.
[TestMethod]
public void TestProcess3()
{
string MyBatchFile = #"C:\sejda-console-3.2.83\bin\sejda-console.bat";
string _sourcePath = #"C:\TestFiles\test.pdf";
string _targetPath = #"C:\TestFiles\split1\";
var process = new Process
{
StartInfo = {
Arguments = String.Format("/C simplesplit --files -f {0} -o {1} -s all", _sourcePath, _targetPath)
}
};
process.StartInfo.FileName = MyBatchFile;
bool b = process.Start();
}
Try this processInfo:
var batch = "sejda-console.bat";
var sourcePath = #"C:\TestFiles\test.pdf";
var targetPath = #"C:\TestFiles\split1\";
var processInfo = new ProcessStartInfo();
processInfo.WorkingDirectory = #"C:\sejda-console-3.2.83\bin";
processInfo.FileName = "cmd.exe";
processInfo.Arguments = $"/C {batch} simplesplit --files -f \"{sourcePath}\" -o \"{targetPath}\" -s all";
// todo set windows style etc
Also have a look at Executing Batch File in C# for error handling.
You are missing /C to send arguments to cmd.exe
Add backslash after \bin\
Wrap your command line arguments with quotes.
So your code should look like:
[TestMethod]
public void TestProcess()
{
string command1 = #"sejda-console simplesplit --files -f C:\TestFiles\test.pdf -o C:\TestFiles\split1\ -s all";
ProcessStartInfo processInfo;
Process process;
//I have the batch file sejda-console in C:\sejda-console-3.2.83\bin so I concatenated the directory of the batch file with the actual command.
processInfo = new ProcessStartInfo("cmd.exe", #"/C \"C:\sejda-console-3.2.83\bin\" + command1 + "\"");
processInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process = Process.Start(processInfo);
process.WaitForExit();
process.Close();
}
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.
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";
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();
All I am trying to do is send a command that opens a model with the program.exe
Supposed to be super simple!
Ex:
"C:\Program Files (x86)\River Logic\Enterprise Optimizer 7.4 Developer\EO74.exe" "C:\PauloXLS\Constraint Sets_1.cor"
The line above works well if pasted on the command prompt window.
However, when trying to pass the same exact string on my code it gets stuck on C:\Program
string EXE = "\"" + #tbx_base_exe.Text.Trim() + "\"";
string Model = "\"" + #mdl_path.Trim()+ "\"";
string ExeModel = EXE + " " + Model;
MessageBox.Show(ExeModel);
ExecuteCommand(ExeModel);
ExeModel is showing te following line on Visual Studio:
"\"C:\\Program Files (x86)\\River Logic\\Enterprise Optimizer 7.4 Developer\\EO74.exe\" \"C:\\PauloXLS\\Constraint Sets_1.cor\""
To me looks like it is the string I need to send in to the following method:
public int ExecuteCommand(string Command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
Things I've tried:
Pass only one command at a time (works as expected), but not an option since the model file will open with another version of the software.
Tried to Trim
Tried with # with \"
Can anyone see any obvious mistake? Thanks.
It's pretty straightforward. You just create a command line object then write to it, then to execute it you read back from it using SR.ReadToEnd():
private string GETCMD()
{
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("#echo on");
SW.WriteLine("cd\\"); //the command you wish to run.....
SW.WriteLine("cd C:\\Program Files");
//insert your other commands here
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
}
Why are you opening a command prompt (cmd.exe)? Just pass the name of the executable.