Subscribe to 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.

| More
This article was originally written on 09/22/06 Tagged with: Programming

Daily Email Updates

You can get our how-to articles in your inbox each day for free. Just enter your name and email below:


Name:
Email:

Comments (5)

  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.


Leave a Comment




Leave your friendly comment here.

If you have a computer help question, click here to leave it on the forums instead.

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

Our Friends
Getting Started


About How-To Geek
What Is That Process?
svchost.exe
jusched.exe
dwm.exe
ctfmon.exe
wmpnetwk.exe
mDNSResponder.exe
wmpnscfg.exe
rundll32.exe
wfcrun32.exe
Ipoint.exe
Itype.exe
Wfica32.exe
Mobsync.exe
conhost.exe
Dpupdchk.exe Adobe_Updater.exe

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