C# - Launch application with arguments. - c#

Hello I've to Launch the software CFast for a Parametric Analysis. To do this, I want to create a application in C# that runs the core CFast.exe. If I want run the software from cmd.exe and execute it on the file INPUTFILENAME.in I write in prompt:
CFast.exe INPUTFILENAME
In C# I wrote the following code:
Process firstProc = new Process();
firstProc.StartInfo.FileName = #"C:\Users\Alberto\Desktop\Simulazioni Cfast\D\C\N\A3B1\CFAST.exe";
firstProc.StartInfo.Arguments = #"INPUTFILENAME";
firstProc.EnableRaisingEvents = true;
firstProc.Start();
firstProc.WaitForExit();
With this code CFast run but doesn't analyze anything... Seems like don't accept the argument. Hint for this trouble ?

Solved. Mistake in the filename and in the syntax of the command
// setup cmd process
var command = #"CFAST.exe C:\Users\Alberto\Desktop\Simulazioni_Cfast\D\C\N\A3B1\A3B1";
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.RedirectStandardError = true;
procStartInfo.CreateNoWindow = true;
// start process
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
// read process output
string cmdError = proc.StandardError.ReadToEnd();
string cmdOutput = proc.StandardOutput.ReadToEnd();
where A3B1 is the name of the file .IN

Related

How to execute the set path=c:\Project Work\jdk1.8.0_66-x64\jre\bin;%PATH% command from C#

I am trying to run an executable JAR file and it has to run using jre version 1.8.
when I run this command manually from CMD I am getting the jre version as 1.8.
set path=c:\Project Work\jdk1.8.0_66-x64\jre\bin;%PATH%
How can I run this command from C#. I tried the following code but not able to execute the command from c#.
try
{
string command = "set path=c:\\Project Work\\jdk1.8.0_66-x64\\jre\bin;%PATH%";
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);
Console.WriteLine(procStartInfo.WorkingDirectory);
Console.ReadLine();
}
catch (Exception objException)
{
// Log the exception
}
Please provide your inputs to execute the command.
I am able to execute the command by following the below steps
1. I have written a batch file with the command
set path=c:\Project Work\jdk1.8.0_66-x64\jre\bin;%PATH%
2. I have named the batch file and executed the batch file from C# program in the following way.
string abc = "abc";
string def = "123";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "C:\\Users\\90008121\\Desktop\\ClassPathbatch.bat";
proc.StartInfo.Arguments = String.Format("{0} {1}", abc, def);
proc.StartInfo.RedirectStandardError = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
Console.ReadLine();
3. Finally the requirement is met.

C# Run CMD as Administrator

I'm trying to run cmd command as administrator. But the CMD window closes unexpectedly. If CMD window stays I can see the error. I tried to use process.WaitForExit();
I am trying to run the code zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk as administrator.
Here is my code.
//The command that we want to run
string subCommand = zipAlignPath + " -v 4 ";
//The arguments to the command that we want to run
string subCommandArgs = apkPath + " release_aligned.apk";
//I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing
//Note: arguments in the sub command need to have their backslashes escaped which is taken care of below
string subCommandFinal = #"cmd /K \""" + subCommand.Replace(#"\", #"\\") + " " + subCommandArgs.Replace(#"\", #"\\") + #"\""";
//Run the runas command directly
ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe");
//Create our arguments
string finalArgs = #"/env /user:Administrator """ + subCommandFinal + #"""";
procStartInfo.Arguments = finalArgs;
//command contains the command to be executed in cmd
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
}
Is there a way to keep the CMD window running/showing?
You are starting a process from the runas.exe executable file. That's not how to elevate a process.
Instead you need to use shell execute to start your excutable, but use the runas verb. Along these lines:
ProcessStartInfo psi = new ProcessStartInfo(...); // your command here
psi.UseShellExecute = true;
psi.Verb = "runas";
Process.Start(psi);
Capture the output(s) from your process:
proc.StartInfo = procStartInfo;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start()
// string output = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();
Then do something with the output.
Note: you shouldn't try to synchronously read both streams at the same time, as there's a deadlock issue. You can either add asyncronous reading for one or both, or just switch back and forth until you're done troubleshooting.
The following method actually works...
private void runCMDFile()
{
string path = #"C:\Users\username\Desktop\yourFile.cmd";
Process proc = new Process();
proc.StartInfo.FileName = path;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.Verb = "runas";
proc.Start();
proc.WaitForExit();
}

COPY command can't find the path specified when run in C#

When I run he following command from the command line it works fine.
COPY "C:\Windows\System32\winevt\Logs\Application.evtx" "C:\ProgramData\MyCompany\Support\Logs\Application.evtx"
But I want to run it using the following in C#
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + CurrentCommand);
StreamReader.procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
while (!proc.StandardError.EndOfStream)
{
sError = proc.StandardError.ReadLine();
//System.Windows.Forms.MessageBox.Show("ERROR: " + sError);
}
proc.WaitForExit();
// Get the output into a string
sResult = proc.StandardOutput.ReadToEnd();
sResult returns the following error:
The system cannot find the path specified
Why is this?
I guess you need to "escape" the command parameters for the cmd /c argument like
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", string.Format("/c \"{0}\"", CurrentCommand));

Executing shell commands in C#

I am trying to execute shell commands [which is supposed to be in cygwin's sh.exe] through a c# program.
Process proc = new Process();
ProcessStartInfo procStartInfo = new ProcessStartInfo(#"C:\cygwin64\bin\sh.exe", "history");
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
proc.StartInfo = procStartInfo;
proc.Start();
But i'm getting the following error instead of getting the list of commands
/usr/bin/sh: history: No such file or directory
Can you please let me know what i'm missing here?
Thanks

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