C# Launch application with multiple arguments - c#

I have been trying to start an application from a C# application but it fails to start properly. From the cmd the application plus the arguments launch a small window showing the output then the application in minimized to the system tray.
Launching the application from the C# application using the code below results in the process appearing in the task manager but nothing else, no output window, no system tray icon. What could be the issue?
myProcess.StartInfo.FileName = ...;
myProcess.StartInfo.Arguments = ...;
myProcess.Start();
also tried passing the following
myProcess.StartInfo.RedirectStandardOutput = true; //tried both
myProcess.StartInfo.UseShellExecute = false; //tried both
myProcess.StartInfo.CreateNoWindow = false;
using
Process.Start(Filename, args)
also did not work. Would really appreciate any help on how to tackle this.
UPDATE:
I think the issue maybe the multiple arguments that are to be passed to the process
RunMode=Server;CompanyDataBase=dbname;UserName=user;PassWord=passwd;DbUserName=dbu;Server=localhost;LanguageCode=9
regards

I don't see any mistake in your code. I have written a little program that prints out its args to the console
static void Main (string[] args)
{
foreach (string s in args)
Console.WriteLine(s);
Console.Read(); // Just to see the output
}
and then I have put it in C:, being the name of the app "PrintingArgs.exe", so I have written another one that executes the first:
Process p = new Process();
p.StartInfo.FileName = "C:\\PrintingArgs.exe";
p.StartInfo.Arguments = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18";
p.Start();
this gives me the desired output of the list of numbers. The app that calls PrintingArgs exits as it reachs p.Start(), this could be avoided by using p.WaitForExit(); or just Console.Read();.
Also I have used both p.UseShellExecute and p.CreateNoWindow. Only in the case that
p.UseShellExecute = false;
p.CreateNoWindow = true;
makes the PrintingArgs app not to show a window (even if I put only p.CreateNoWindow = true it shows a window).
Now it comes to my mind that maybe your are passing the args in a wrong way and makes the other program to fail and close inmediately, or maybe you are not pointing to the right file. Check paths and names, in order to find any mistake you could omit.
Also, using
Process.Start(fileName, args);
does not uses the info you set up with StartInfo into your Process instance.
Hope this will help,
regards

Not sure if anyone is still following this but here is what I came up with.
string genArgs = arg1 + " " + arg2;
string pathToFile = "Your\Path";
Process runProg = new Process();
try
{
runProg.StartInfo.FileName = pathToFile;
runProg.StartInfo.Arguments = genArgs;
runProg.StartInfo.CreateNoWindow = true;
runProg.Start();
}
catch (Exception ex)
{
MessageBox.Show("Could not start program " + ex);
}
Adding a space in the string allowed two arguments to be passed into the program I wanted to run. The program ran without issue after executing the code.

Have u set your ProcessWindowStyle to Hidden?
This is my code, working fine:
Process p=new Process();
p.StartInfo.FileName = filePath;//filePath of the application
p.StartInfo.Arguments = launchArguments;
p.StartInfo.WindowStyle = (ProcessWindowStyle)ProcessStyle;//Set it to **Normal**
p.Start();

System.Diagnostics.Process.Start(FileName,args);
Eg
System.Diagnostics.Process.Start("iexplore.exe",Application.StartupPath+ "\\Test.xml");

Related

How to run R.exe without args in WPF

I create a process to run 'cmd.exe' and redirect the stdout,stderr,stdin.
It seems work good. But when I input 'R' and try to run 'R.exe', it doesn't work and show the message below.
Fatal error: you must specify '--save','--no-save' or '--vanilla'
Process _process = new Process();
ProcessStartInfo _startInfo = new ProcessStartInfo();
_startInfo.FileName = "cmd.exe";
_startInfo.Arguments = "";
_startInfo.RedirectStandartInput = true;
_startInfo.RedirectStandartOutput = true;
_startInfo.RedirectStandartError = true;
_startInfo.CreateNoWindows = true;
I expect that the process which is runing 'cmd.exe' can run R.exe after inputting 'R' without another args.
Current Output
Expected Output
I have try to input the full path to the executable. It show the same result.
But if the ProcessStartInfo is changed, it does work as I expect.
_startInfo.CreateNoWindows = false;
And I find an interesting appearance.
When CMD is running in system process, I try to redirect the output of R.exe and input "R > D:\a.txt". And the fatal error message will be alse shown.

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

Embedding a CMD terminal in a C# Winforms application

What I intend to do is build an application which, among other things, will have a command line embedded in it just like some IDEs do (something I find extremely useful).
This is the code that I have so far, do note that it's a Winforms project:
public partial class Form1 : Form
{
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
p.StartInfo = info;
p.Start();
}
private void button1_Click(object sender, EventArgs e) {
using(StreamWriter sw = p.StandardInput) {
if(sw.BaseStream.CanWrite) {
sw.WriteLine(textBox1.Text);
}
}
textBox2.Text = p.StandardOutput.ReadToEnd();
textBox3.Text = p.StandardError.ReadToEnd();
p.WaitForExit();
}
}
}
As you can see there are 3 textboxes and one button:
textbox1 is for entering the command
textbox2 is for stdout
textbox3 is for stderr
On to my problem:
I can only input one command because after executing it, my CMD window vanishes. I know it dies off because I've set info.CreateNoWindow = false; and it indeed vanishes and if I try to enter another command I get an exception.
How would I go on about keeping my CMD window 'alive' so that I can use it as much as I please? In short I want to truly mimic CMD behavior.
Feel free to ask for more information if something is not clear.
Extra info/What I tried:
I've tried adding info.Attributes = "/K"; since I know that /K should keep the CMD alive. I've also read that p.WaitForExit(); should keep the CMD alive, but from what I figured this is only for the purpose of reading the output. Needless to say, I do not need that since I'm already redirecting its output. Neither of these solutions work but it is entirely possible that I'm using them the wrong way.
I need that process alive so I can easily navigate using cd and executing a sequence of commands when needed, such as when accessing ftp or mysql. I know I can work around these two examples with parameters, but not for every application. In short, spawning a new process every time is not something I want. I want that CMD interface to be up at all times.
The cmd process dies after
using(StreamWriter sw = p.StandardInput) {
if(sw.BaseStream.CanWrite) {
sw.WriteLine(textBox1.Text);
}
}
But I cannot pinpoint why.
What CMD console provides is an interface to execute predefined functions (in System32 or in %PATH%). Process class also have same capabilities ,what you can do is as the user enters command text and presses return key in textbox2 (which can be multi-lined, black-background, white text) you can pass the command text to Process p = new Process();and append the result so it looks like single cmd session. Now before passing the whole command text we need to separate arguments (if any) which is text appearing after first space. Example:
SHUTDOWN /S /T 10
where Shutdown will be filename and /S /T 10 will be arguments.
Before executing set default directory of ProcessStartInfo:-
_processStartInfo.WorkingDirectory = #"%Path%";
Otherwise default will be System32 folder.

Running Phantomjs using C# to grab snapshot of webpage

I'm trying to grab snapshots of my own website using phantomjs - basically, this is to create a "preview image" of user-submitted content.
I've installed phantomjs on the server and have confirmed that running it from the command line against the appropriate pages works fine. However, when I try running it from the website, it does not appear to do anything. I have confirmed that the code is being called, that phantom is actually running (I've monitored the processes, and can see it appear in the process list when I call it) - however, no image is being generated.
I'm not sure where I should be looking to figure out why it won't create the images - any suggestions? The relevant code block is below:
string arguments = "/c rasterize.js http://www.mysite.com/viewcontent.aspx?id=123";
string imagefilename = #"C:\inetpub\vhosts\mysite.com\httpdocs\Uploads\img123.png";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.FileName = #"C:\phantomjs.exe";
p.StartInfo.Arguments = arguments + " " + imagefilename;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
I check the errors that phantomjs throws during its process.
You can read them from Process.StandardError.
var startInfo = new ProcessStartInfo();
//some other parameters here
...
startInfo.RedirectStandardError = true;
var p = new Process();
p.StartInfo = startInfo;
p.Start();
p.WaitForExit(timeToExit);
//Read the Error:
string error = p.StandardError.ReadToEnd();
It will give you an idea of what happened
The easiest way for executing phantomjs from C# code is using wrapper like NReco.PhantomJS. The following example illustrates how to use it for rasterize.js:
var phantomJS = new PhantomJS();
phantomJS.Run( "rasterize.js", new[] { "https://www.google.com", outFile} );
Wrapper API has events for stdout and stderr; also it can provide input from C# Stream and read stdout result into C# stream.

Categories