The .NET blog

The Process class: Starting an application or URL

May 21, 2009

The Process class from the System.Diagnostics namespace can be quite useful, especially for launching other applications or even URL’s. An application can be started with a single line of code:

Process.Start(@"C:\Windows\System32\calc.exe");

It doesn’t get simpler than that, in a perfect world. But as we all know, the world is not perfect, and that line could go wrong for a number of reasons, the most simple one being that the path I specified doesn’t fit with your computer. We should obviously handle any exception thrown, like this:

try
{
	Process.Start(@"C:\Windows\System32\calc.exe");
}
catch(Exception ex)
{
	MessageBox.Show("Could not start the file: " + ex.Message);
}

In case the file can’t be found, a specific FileNotFoundException will be thrown, which you could handle differently than other exceptions, but to keep it simple, we just catch all exceptions and treat them the same way.

Now, perhaps you want to include a parameter or something like that. The Process.Start() method does have an overload that takes a set of arguments, but it also comes with one that takes a ProcessStartInfo object, which makes you capable of doing some pretty advanced stuff. For instance, have a look at this example:

try
{
	ProcessStartInfo processStartInfo = new ProcessStartInfo();
	processStartInfo.FileName = @"C:\Windows\System32\notepad.exe";
	processStartInfo.Arguments = @"C:\somedocument.txt";
	processStartInfo.WindowStyle = ProcessWindowStyle.Minimized;
	Process.Start(processStartInfo);
}
catch(Exception ex)
{
	MessageBox.Show("Could not start the file: " + ex.Message);
}

We specify that the file to be started is Windows Notepad, that the arguments should be a .txt file on my local computer (create this file or specify another path to make this work on your computer), and that the application window of this new process should be minimized from the start. This code will launch Notepad, load the specified file and make the window minimized. There are many more cool options, which you can investigate on your own. To end this post, I want to mention that launching an URL is just as simple as an application:

try
{
	Process.Start("http://blog.net-tutorials.com");
}
catch(Exception ex)
{
	MessageBox.Show("Could not start the URL: " + ex.Message);
}

This will simply launch this fine blog in your default browser. Enjoy :)

Filed under: C# — admin @ 10:09 am

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment




© net-tutorials.com 2006 - 2012