SEARCH

How-To Geek

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.

Lowell Heddings, better known online as the How-To Geek, spends all his free time bringing you fresh geekery on a daily basis. You can follow him on if you'd like.

  • Published 09/22/06

Comments (9)

  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.

  3. Horacio

    Hey there! I`m struggling to get this work, but I`m getting constantly the path of the app (C:\User Profiles\Marisa\Escritorio\hachito\WindowsApplication1\WindowsApplication1\bin\Debug\WindowsApplication1.exe) instead of the parameter. I copy the .exe from the debug directory and then from the command line try to invoke the .exe with WindowsApplication1 (“hello world”), WindowsApplication1 “hello world”, WindowsApplication1(hello world), etc and it doesnt work… any clue? thanks for your time!!

  4. Suirik

    thank you !!!!

  5. Arnab

    Great! I was just looking for it.

  6. Rahul

    Fantastic !

  7. Abir

    Great, its just what I needed!

    Horacio: the zero indexed parameter (args[0]) is the currently running executable’s path, use args[1] for the first argument

  8. Simon

    Fabulous, thanks.
    And what Abir said!

  9. Manh Le

    Awsome cool!
    Just what I need

Enter Your Email Here to Get Access for Free:

Go check your email!