Reputation: 130
Visual Studio 2010 C#
Is it possible to run and close a program from commandline? I need to do something like that:
myProgram.exe -start
-- do something --
myProgram.exe -stop
I know how to implement the first part (String[] args in main) but how can I close my running program?
Edit
myProgram.exe is handling some UDP communication and have to be executed while the stuff in -- do something -- is executed. Sorry for beeing imprecise.
Upvotes: 1
Views: 2177
Reputation: 45109
As Fox32 already mentioned in his comment you should really take this approach, cause in that case your application can really shutdown itself gracefully. If you simply go and use taskkill, etc to kill your process from the outer world you could really get into trouble depending of resources you are using (network, database, files, etc.).
Upvotes: 0
Reputation: 16575
I'm guessing you know how to inspect the command line arguments and find if stop has been specified? The following should do the job.
var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
var matchingProcesses = System.Diagnostics.Process.GetProcesses().Where(x => x.Id != currentProcess.Id && x.ProcessName == currentProcess.ProcessName);
foreach (var process in matchingProcesses) {
process.Kill();
}
Upvotes: 1