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

Actions

Information

One response

15 04 2009
Andy Bailey

Thanks, I’ll try this. I would like to know if this works with multiple commands in the same process. I’ll experiment and report back.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: