Posted on

Utilizing C#: Running External Programs

I’ve built a handful of neat little helper programs that both utilize C# and completely separate software.  As I’ve dug back into the details of some of them recently – I’m going to take the time to share some ‘tips-n-tricks’ with you that I’ve picked up.

A lot of this will certainly be a reference for myself (always comment your code people!) but I hope it can come in handy for you too.

FYI most of these are going to assume that you have some programming and C# knowledge.  But as always – if you’re interested in learning more or asking questions, tweet me.

Today’s example is a conundrum I ran into when I was first starting to work with external programs.  I wanted to have my own UI and a bunch of settings, and when I hit the “go” button I wanted my UI to launch a separate program with the settings I’d just established.

But how to launch that 2nd program from mine?

What you’re looking for within C# is the Process class.  For example:

// Create a new Windows process called "proTools"
Process proTools = new Process();

Keep in mind here that “proTools” is nothing more than the arbitrary name for your process.  It might look like Pro Tools, but it’s not yet.  Instead, you’ve just created a Process object with no real definition yet.

So how do you define it?

Two steps:

  1. Make sure that the program you’re trying to run actually exists
  2. Give the Process some startup info, including a filename

For example, that would look something like this:

if(File.Exists("C:\\Pro Tools\\Pro Tools.exe"))
{
proTools.StartInfo.FileName = "C:\\Pro Tools\\Pro Tools.exe";
}

Realistically if you know you have a program installed in a certain location, you don’t have to do that first step.  Also if you’re releasing a program for users other than yourself you’re going to want to abstract the file location more than what I’ve written above.

However, all that the above is saying – if you’re lost – is:

  1. If “Pro Tools.exe” exists in “C:\Pro Tools\”
  2. Then tell the Process proTools that the file to use when you start the Process is “C:\Pro Tools\Pro Tools.exe”

But why did I have to use two backslashes “\\” in the file location string?  Because C# reads a single backslash as an invisible character.  Such as if you want to print on a new line you use “\n” much like you’d press Enter on a word processor.  So you need two slashes, as C# will pick up the 2nd one as an actual backslash.

Now that I’ve explained that, to actually start the process, all you have to do is use:

proTools.Start();

Fairly simple right?


Copyright 2016-2021, NIR LLC, all rights reserved.