Running command line commands from C#

2 04 2009

I needed to make a Windows Service that watched folders defined in an XML file for any new events. Upon a new file being created, I needed to call an executable file and pass some arguments via the command line for each file in the folder, and the executable needed to be called sequentially.

I had various issues with this. Upon my research I discovered there are multiple ways to do this. Not only multiple ways to write to the command line, but also I could have done it via a batch file. My solution required writing directly to the command line however, and below is the code I used in my final realease.

Process runMap = new Process();
runMap.StartInfo.WorkingDirectory = @"C:/Project/maps";
runMap.StartInfo.FileName = @"C:/Project/executables/dstx.exe";
runMap.StartInfo.Arguments = TRIGGER_MAP + " -b";
runMap.Start();
runMap.WaitForExit();
runMap.Close();

In my case, the WaitForExit() command is important because I need each file to run one at a time. The Close() is important, otherwise the Process will stay open and your processes in your Task Manager will fill with whatever executable you are calling.

As I said, there are so many ways of doing this. This is just the one that worked for me. If this one doesn’t work for you, you have plenty of other options! If anyone reading this is having a problem getting this code to run in a Windows Service like I was, and it doesn’t seem to be working, make sure your service is able to interact with the desktop! I had the same problem 🙂

Advertisements