How to run c# console application .exe in background? - c#

I'm trying to simulate the updating of a database using commands in cmd but I need to be able to run the .exe that calls these from a cmd and continue to use that same cmd window.
I've attempted to just hide the window that Process will create, which works fine, however when I run myFile.exe it hangs up the cmd window used to run it until the process is finished. This is a problem because when completed my code will be running for hours at a time and I would rather not keep a dead cmd window open just to run the application.
Currently ProcessWindowStyle.Hidden is what I am using to call the command and hide the window, the command sets the first value in my database to the numbers 0-25 every half second but I can't use the cmd window until it reaches 25 and exits the application.
static void Main(string[] args)
{
int Number_Of_Args = args.Length;
int[] Arguments = Check_Args(args, Number_Of_Args);
Run_Command(Arguments);
}
public static void Run_Command(int[] Arguments)
{
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";
for (int i = 0; i <=25 ; i++)
{
startInfo.Arguments = "/C dbset 1 = " + i.ToString();
process.StartInfo = startInfo;
process.Start();
Thread.Sleep(500);
}
}
When complete I need the for loop to be a while loop that will continuously change the database values and therefor having it hang in the cmd window is not ideal. My final goal is be able to call my application from cmd with "C:\filelocation Simulation.exe arg1 arg2 arg3" and have it start running and updating the database while I go about whatever other business I have with the cmd window at the time.
EDIT: I can call Start Simulation.exe and it will open a new cmd window and run the code in a new window and leaves me in control of the original window. If I could either have Start Simulation.exe hide the new cmd window OR have the code default to Start a new window when called simply as Simulation.exe that could be what I need, although having both would be the best, like previously stated, so that I can run the command and not lose control of the current cmd window.

I did some searching and if I understood you right, I think you can achieve what you want with:
start /B ConsoleApp.exe
Source:
How can I execute a Windows command line in background?

Related

Executing cmd commands with complex output in c#

I often find myself using different commands on pc's to check stuff in the system and I wanted to basically create a small standalone exe that will execute all my common commands and give me the output of each of them without me entering them manually...
I want to note that I know this isn't the first question on google on the subject of executing a cmd command with c# but non fit my command requirements, for example many of them execute commands such as copy or move or make and non of them have a complex output, I want to execute for example the "sfc /scannow" command, which outputs a progress bar which measures the progress of course and a final output, the issue with that is I have tried many ways to attempt that but all failed, a shell execution works very well with opening another cmd windows and even requiring elevation but as soon as the progress bar ends and it displays the final output it crashes (and thus I can't see the final output), with shell execution off (executing via the main window) it either doesn't show the progress bar at all and just shows the final output, or shows nothing, or it does show the progress bar, but with each increment it's a new line which obviously doesn't look right...
this is my code:
public static void ExecuteCommand(string command) {
Process prc = new Process();
ProcessStartInfo info = new ProcessStartInfo
{
Verb = "runas",
FileName = "cmd.exe",
UseShellExecute = true,
Arguments = "/c" + command
};
prc.StartInfo = info;
prc.Start();
prc.WaitForExit();
prc.Close();
}
if anyone can think of a fix please do tell me, I have been stuck on this for about 3 days...
Turns out the culprit was "/c", if I change it to "/K" the windows stays open until I close it manually like I wanted.

Wait for cmd command to end before continuing

I run a command from the command window like this:
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 = "/C " + command + "> " + userProfile + #"\cmdoutput.txt";
process.StartInfo = startInfo;
process.Start();
The next line of code reads the text file and manipulates the data as needed. However, if I don't wait for the cmd process to end it will read an empty text file. I have thought of:
Not using a text file
This won't work due to other restrictions I have, it does need to be put in a text file
Wait a few seconds
I don't know how long the command will take, and time-based solutions are generally bad anyway.
Check if the command prompt process is running
The user may be running another command prompt for whatever reason
The System.Diagnostics.Process class has a method, WaitForExit. As I understand your question, that should do what you're looking for.
You should be able to just do,
process.Start();
process.WaitForExit();
You can also pass an int for a timeout, if necessary.
This, of course, assumes that the application you're running will exit after it's done. If that's not the case (reconsider that!), you'll have to do something else, like polling.

launch exe with params, but program closes instantly after opening?

I am writing a client for my gaming community and one of the functions of this client is to launch a game via the client with parameters that will enable our community mod pack on launch.
When I press the button, the game begins to launch and as soon as the program opens (the icon pops up in the task bar), it closes instantly.
Is there something I am missing that is needed to keep the launched exe running?
Here is my code:
private void btnLaunchGame_Click(object sender, EventArgs e)
{
string armaPath = gameDir+"/Expansion/beta/";
string filename = Path.Combine(armaPath, "arma2oa.exe");
string launchParams = "-noSplash -noFilePatching -showScriptErrors \"-name=Meta\" \"-mod=I:/Steam/steamapps/common/Arma 2;expansion;expansion/beta;expansion/beta/expansion;servermods/#HC_DAYZ;servermods/#HC_WEAPONS;servermods/#HC_EXTRAS;servermods/#HC_ACE\"";
System.Diagnostics.Process.Start(filename, launchParams);
}//close Game Launch
Any ideas is appreciated!
I have a .bat file that will execute the game flawlessly with the launch args listed below, this could possibly help pinpoint the cause of my problem:
http://puu.sh/5CGKk.png (couldn't get code to paste in a readable format).
Try using Process:
Process process = new Process();
process.StartInfo.FileName = "arma2oa.exe";
process.StartInfo.Arguments = "-noSplash -noFilePatching -showScriptErrors \"-name=Meta\" \"-mod=I:/Steam/steamapps/common/Arma 2;expansion;expansion/beta;expansion/beta/expansion;servermods/#HC_DAYZ;servermods/#HC_WEAPONS;servermods/#HC_EXTRAS;servermods/#HC_ACE\"";
process.StartInfo.WorkingDirectory = gameDir + "/Expansion/beta/";
process.Start();
It may be what exe require working directory to be set. Or it will crash, unable to load resources.
If that doesn't works, then perhaps you need to add
process.WaitForInputIdle();
before exiting function running process. I don't know why, but running Acrobat Reader without this wait may sometimes cause a wierd effect: Acrobat is running, but the document, passed via arguments, is not shown. Perhaps something to do with Garbage collector or Process itself.
Try following
using (Process process = new Process())
{
ProcessStartInfo startInfo = new ProcessStartInfo("C:\Program Files\Arma2oa\Arma2oa.exe");
startInfo.Arguments = "-noSplash -noFilePatching -showScriptErrors \"-name=Meta\" \"-mod=I:/Steam/steamapps/common/Arma 2;expansion;expansion/beta;expansion/beta/expansion;servermods/#HC_DAYZ;servermods/#HC_WEAPONS;servermods/#HC_EXTRAS;servermods/#HC_ACE\"";
process.StartInfo = startInfo;
process.Start();
}

How to change the current directory via ProcessStartInfo and cmd

At the moment I'm developing a small wrapper around CMD using ProcessStartInfo, trying to emulate the command window and adding some extra functionality that I desperately need.
This WINFORM application is a multitab app so that you can start multiple 'sessions'. Furthermore, since the content is stored in a richtextbox, I can easily copy it and more importantly search the console log.
Up till now everything seems to work fine, but when I ask for the current directory, I see the location of this app, which is fine. But when I go one directory up, it does not seem to work.
I'm pretty sure I'm doing something wrong. Could somepoint point me out what it is, what I'm doing wrong? Here is the code excerpt that deals with the execution of the code.
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.UseShellExecute = false;
// Do not create window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(onOutputDataReceived);
proc.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(onErrorDataReceived);
proc.Start();
proc.StandardInput.WriteLine("/c " + cmd);
proc.StandardInput.Close();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
You seem to be starting a new process each time you want to execute a command. If you want the environment (like current path) to stay the same between commands, you will need to either save the environment and load it into your new process, or keep a single process open.

How to close an external application using c#

Im trying to be close the calculator when the user press's a key on the key board. But p.kill and p.CloseMainWindow doesn't kill the calculator, only the shell which is executed.
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.Arguments = "/c calc ";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.Start();
Console.WriteLine("Press any key to kill Calc");
Console.ReadKey();
p.CloseMainWindow();
p.Kill();
Don't use the shell (cmd) but run the calc process directly. Setting Process.StartInfo.FileName to "calc" should do it (assuming calc.exe is on the system path).
You need to find the Calculator process and kill it. There are actually two processes created: one for the cmd and the other for Calculator. You are killing only the first one.
The other solution is to start the Calculator directly, without using cmd.
because your process is not the calc.exe process but the command prompt which executes the calc.
to find a process by name and kill it, you should use GetProcessByName,
see an example here: C# Process Process.GetProcessesByName, Kill Process and Exit Event

Categories

Resources