Execute a program from the cmd with arguments - c#

I have a program that needed running from the cmd with arguments, say the execute file called
program.exe
And i need to run it from the cmd with args, the whole command in the cmd look like this:
c:\ram\program.exe /path = c:\program files\NV
As you can see the path is : "c:\ram\"
The execute file is : "program.exe"
The args that i need to send is : /path = c:\program files\NV
How can i do it ?
I try to open process like this :
string strArguments = #"/path = c:\program files\NV";
Process p = new Process();
p.StartInfo.FileName = "program.exe";
p.StartInfo.WorkingDirectory = "c:\\ram\\";
p.StartInfo.Arguments = strArguments;
p.Start();
And its not good, i figure that the problem could be that i'm not accessing the exe file from the CMD, maybe i'm wrong...any body got idea how can i do it ?
Thanks

Try these things
p.StartInfo.FileName = "c:\\ram\\program.exe"; without setting Working Directory
and this one is more likely the source of the problem
string strArguments = #"/path = ""c:\program files\NV""";
When there is a space in a path, you have to enclose the whole path in quotation marks. The complete code is as follows
string strArguments = #"/path=""c:\program files\NV""";
Process p = new Process();
p.StartInfo.FileName = #"c:\ram\program.exe";
p.StartInfo.Arguments = strArguments;
p.Start();
It should do exactly what are you trying to do.
1.run "cmd.exe".
2.go to this dir: "c:\ram\" (in the cmd of course).
3.execute the file "program.exe" with this argument: "/path = c\:program files\NV"
It takes the program.exe in the c:\ram\ folder and executes it using cmd with the specified arguments.

Related

Getting the command prompt c#

The following code executes a .exe file on the local machine and generates a new file .obj based on an .ifc file in the same directory. .obj (new one) and .ifc should have the same name (no problem).
if (clicked) {
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WorkingDirectory = "C:\...";
string arg1;
arg1 = "#/c command" // run .exe appliaction
p.StartInfo.Arguments = arg1;
p.Start();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.WaitForExit();
}
If the user clicked the button one more time (the code gets run again), a new cmd appears and tells him that the file already exists. Does he want to override:
(y/n) would be the argument in this case.
Now I want to capture that new cmd and replace it with a "yes/no" window, so that the user wont see it. How is this possible?

C# Call EXE from console app

I have a console app that does a number of things. One of the steps involves calling an EXE (AzCopy). I've successfully run this type command in a prompt and it looks like this:
AzCopy /Source:https://mysite.table.core.windows.net/MYTABLE/ /SourceKey:SOURCEKEY /Dest:C:\export /Manifest:MYTABLE
I need to run this script in the middle of a console app's execution. I've seen a number of different ways to do this, but none seem to work. I've tried this:
System.Diagnostics.Process.Start("CMD.exe", command);
And this:
var procStartInfo = new ProcessStartInfo("AzCopy", command);
And this:
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = command;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
None seem to actually kick off the AzCopy call. What gives?
System.Diagnostics.Process.Start("CMD.exe", command); should work.
But you need to add /C at the beginning of your command.
Something like this:
"/C AzCopy /Source:https://mysite.t........................................."

Run an exe with command-line parameters

I have an exe that I would like to use by executing it with command line parameters.
var query = Path.Combine(path, calculator.ExeName + ".exe");
var p = new Process();
p.StartInfo.FileName = query;
//the command line parameter that causes the exe to start in an invisible mode
p.StartInfo.Arguments = "episrc"
p.Start();
This code works and it starts the exe but there's one problem : the exe is supposed to be writing on a file in its directory but that doesn't happen. The process exits successfully (Exitcode0). What could be the cause of this problem?
I have a Delphi code that executes successfully the exe and the exe writes to the file but it's using the ExecProcess from win32 API thus the exe is valid and working.
Also if I try to execute it from the command prompt like so : kowwinnt.exe episrc it writes to the file successfully.
You should set the Working Directory.
Your code would look like this:
var query = Path.Combine(path, calculator.ExeName + ".exe");
var p = new Process();
p.StartInfo.FileName = query;
p.StartInfo.WorkingDirectory = path;
//the command line parameter that causes the exe to start in an invisible mode
p.StartInfo.Arguments = "episrc"
p.Start();

Trying to use cmd via c#

I am trying to use a cmd command prompt that works just fine when I use it in a normal cmd window via Windows --> Start --> cmd
My code looks like this
"C:\Program Files\Rapid-I\RapidMiner5\scripts\rapidminer.bat" -f
"C:\Users\user\.RapidMiner5\repositories\Local Repository\test.rmp"
That works just fine.
The problem is when I am trying to write this code in C# by opening a cmd window via C#
This is the c# code
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/c \"C:\\Program Files\\Rapid-I\\RapidMiner5\\scripts\\rapidminer.bat\" -f \"C:\\Users\\user\\.RapidMiner5\\repositories\\Local Repository\\test.rmp\"");
You can see I quoted the same way like the code that work in the regular cmd
But I am getting a can't recognize program files.
Try this:
string fullPath = #"C:\Program Files\Rapid-I\RapidMiner5\scripts\rapidminer.bat";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = Path.GetFileName(fullPath);
p.WorkingDirectory = Path.GetDirectoryName(fullPath);
p.Arguments = #"/c -f ""C:\Users\user\.RapidMiner5\repositories\Local Repository\test.rmp""";
Process.Start(p);
I modified my original code to add arguments to your process.
One last thing you could try is putting your original command into a batch file and calling the batch file from your ProcessStartInfo object like so:
C#:
string fullPath = #"C:\Program Files\Rapid-I\RapidMiner5\scripts\run.bat";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = Path.GetFileName(fullPath);
p.WorkingDirectory = Path.GetDirectoryName(fullPath);
Process.Start(p);

C#.Net: Why is my Process.Start() hanging?

I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code:
SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = #"c:\build";
psi.FileName = Environment.SystemDirectory + #"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "builder";
psi.Password = password;
Process.Start(psi);
If you didn't guess, this batch file builds my application (a different application than the one that is executing this command).
The Process.Start(psi); line returns immediately, as it should, but the batch file just seems to hang, without executing. Any ideas?
EDIT: See my answer below for the contents of the batch file.
The output.txt never gets created.
I added these lines:
psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
String outp = p.StandardOutput.ReadLine();
and stepped through them in debug mode. The code hangs on the ReadLine(). I'm stumped!
I believe I've found the answer. It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here:
http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx
That won't work for me, because my batch file uses IF and GOTO, but it would definitely work for simple batch files.
Why not just do all the work in C# instead of using batch files?
I was bored so i wrote this real quick, it's just an outline of how I would do it since I don't know what the command line switches do or the file paths.
using System;
using System.IO;
using System.Text;
using System.Security;
using System.Diagnostics;
namespace asdf
{
class StackoverflowQuestion
{
private const string MSBUILD = #"path\to\msbuild.exe";
private const string BMAIL = #"path\to\bmail.exe";
private const string WORKING_DIR = #"path\to\working_directory";
private string stdout;
private Process p;
public void DoWork()
{
// build project
StartProcess(MSBUILD, "myproject.csproj /t:Build", true);
}
public void StartProcess(string file, string args, bool redirectStdout)
{
SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
p = new Process();
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.WorkingDirectory = WORKING_DIR;
psi.FileName = file;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = redirectStdout;
psi.UserName = "builder";
psi.Password = password;
p.StartInfo = psi;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
p.Start();
if (redirectStdout)
{
stdout = p.StandardOutput.ReadToEnd();
}
}
void p_Exited(object sender, EventArgs e)
{
if (p.ExitCode != 0)
{
// failed
StringBuilder args = new StringBuilder();
args.Append("-s k2smtpout.secureserver.net ");
args.Append("-f build#example.com ");
args.Append("-t josh#example.com ");
args.Append("-a \"Build failed.\" ");
args.AppendFormat("-m {0} -h", stdout);
// send email
StartProcess(BMAIL, args.ToString(), false);
}
}
}
}
Without seeing the build.cmd it's hard to tell what is going on, however, you should build the path using Path.Combine(arg1, arg2); It's the correct way to build a path.
Path.Combine( Environment.SystemDirectory, "cmd.exe" );
I don't remember now but don't you have to set UseShellExecute = true ?
Another possibility to "debug" it is to use standardoutput and then read from it:
psi.RedirectStandardOutput = True;
Process proc = Process.Start(psi);
String whatever = proc.StandardOutput.ReadLine();
In order to "see" what's going on, I'd suggest you transform the process into something more interactive (turn off Echo off) and put some "prints" to see if anything is actually happening. What is in the output.txt file after you run this?
Does the bmail actually executes?
Put some prints after/before to see what's going on.
Also add "#" to the arguments, just in case:
psi.Arguments = #"/q /c build.cmd";
It has to be something very simple :)
My guess would be that the build.cmd is waiting for some sort of user-interaction/reply. If you log the output of the command with the "> logfile.txt" operator at the end, it might help you find the problem.
Here's the contents of build.cmd:
#echo off
set path=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;%path%
msbuild myproject.csproj /t:Build > output.txt
IF NOT ERRORLEVEL 1 goto :end
:error
bmail -s k2smtpout.secureserver.net -f build#example.com -t josh#example.com -a "Build failed." -m output.txt -h
:end
del output.txt
As you can see, I'm careful not to output anything. It all goes to a file that gets emailed to me if the build happens to fail. I've actually been running this file as a scheduled task nightly for quite a while now. I'm trying to build a web app that allows me to run it on demand.
Thanks for everyone's help so far! The Path.Combine tip was particularly useful.
I think cmd.exe hangs if the parameters are incorrect.
If the batch executes correctly then I would just shell execute it like this instead.
ProcessStartInfo psi = new ProcessStartInfo();
Process p = new Process();
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.WorkingDirectory = #"c:\build";
psi.FileName = #"C:\build\build.cmd";
psi.UseShellExecute = true;
psi.UserName = "builder";
psi.Password = password;
p.StartInfo = psi;
p.Start();
Also it could be that cmd.exe just can't find build.cmd so why not give the full path to the file?
What are the endlines of you batch? If the code hangs on ReadLine, then the problem might be that it's unable to read the batch fileā€¦

Categories

Resources