How to run a command using System.Diagnostics.Process? - c#

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();
}

Related

C# CMD with command not executed [duplicate]

In C# WPF: I want to execute a CMD command, how exactly can I execute a cmd command programmatically?
Here's a simple example :
Process.Start("cmd","/C copy c:\\file.txt lpt1");
As mentioned by the other answers you can use:
Process.Start("notepad somefile.txt");
However, there is another way.
You can instance a Process object and call the Start instance method:
Process process = new Process();
process.StartInfo.FileName = "notepad.exe";
process.StartInfo.WorkingDirectory = "c:\temp";
process.StartInfo.Arguments = "somefile.txt";
process.Start();
Doing it this way allows you to configure more options before starting the process. The Process object also allows you to retrieve information about the process whilst it is executing and it will give you a notification (via the Exited event) when the process has finished.
Addition: Don't forget to set 'process.EnableRaisingEvents' to 'true' if you want to hook the 'Exited' event.
if you want to start application with cmd use this code:
string YourApplicationPath = "C:\\Program Files\\App\\MyApp.exe"
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.FileName = "cmd.exe";
processInfo.WorkingDirectory = Path.GetDirectoryName(YourApplicationPath);
processInfo.Arguments = "/c START " + Path.GetFileName(YourApplicationPath);
Process.Start(processInfo);
Using Process.Start:
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("example.txt");
}
}
How about you creat a batch file with the command you want, and call it with Process.Start
dir.bat content:
dir
then call:
Process.Start("dir.bat");
Will call the bat file and execute the dir
You can use this to work cmd in C#:
ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = #"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();
Don't forget to write /c before your argument !!
Argh :D not the fastest
Process.Start("notepad C:\test.txt");
Are you asking how to bring up a command windows? If so, you can use the Process object ...
Process.Start("cmd");
You can do like below:
var command = "Put your command here";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.WorkingDirectory = #"C:\Program Files\IIS\Microsoft Web Deploy V3";
procStartInfo.CreateNoWindow = true; //whether you want to display the command window
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
label1.Text = result.ToString();
In addition to the answers above, you could use a small extension method:
public static class Extensions
{
public static void Run(this string fileName,
string workingDir=null, params string[] arguments)
{
using (var p = new Process())
{
var args = p.StartInfo;
args.FileName = fileName;
if (workingDir!=null) args.WorkingDirectory = workingDir;
if (arguments != null && arguments.Any())
args.Arguments = string.Join(" ", arguments).Trim();
else if (fileName.ToLowerInvariant() == "explorer")
args.Arguments = args.WorkingDirectory;
p.Start();
}
}
}
and use it like so:
// open explorer window with given path
"Explorer".Run(path);
// open a shell (remanins open)
"cmd".Run(path, "/K");

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";

string format in c# running command line

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>\"";

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();

Execute command line using C#

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.

Categories

Resources