Subscribe to How-To Geek

Recommended: Click Here to Run a Free Scan for Common PC Errors   [Sponsored Link]

Get Command Line Arguments in a Windows Forms Application

A useful technique for your applications is allowing them to parse command line arguments. This can give a lot of extra functionality to your application, for instance to pass the name of a file to open on the command line.

Most of the examples you'll find online will show you something like this:

static void Main(string[] args)
{
    foreach(string arg in args)
    {
       Console.WriteLine(arg);
    }
   Console.ReadLine();
}

That's all fine and good, except that won't work for our Windows Forms application without changing the type of the project to console, etc.

Thankfully, this is completely unnecessary, because you can simply do this:

string[] args = Environment.GetCommandLineArgs();

foreach(string arg in args){
// do stuff
}

And you can use this anywhere in your application, you aren't just restricted to using it in the main() method like in a console application.

The Geek is the founder of How-To Geek and a geek enthusiast. When he's not coming up with great how-to articles, he's probably writing at his personal blog. This article was written on 09/22/06 and tagged with: Programming, C#

Comments (2)

  1. mg

    or you can just add string[] args to the main in your windows forms app. its all the same main() whether its console or winforms

  2. Sorin

    You might prefer to use args[] string added to main, otherwise using Environment you will get the parameter with the path to the executable.


Leave a Comment




Leave your friendly comment here. If you have a computer help question, leave it on the forums instead.

Note: Your comment may not show up immediately on the site.

Copyright © 2006-2008 HowToGeek.com. All Rights Reserved.