Get command line arguments in C#

One method to do this is to override the program’s Main method and give it a parameter that is a string array as in the following code.

static void Main(string[] args)
    foreach (string arg in args)

This method was sort of inherited from the C programming language.

I prefer the following method, partly because you don’t need to mess with Main and partly because it lets you check the command line arguments anywhere in the program.

private void Form1_Load(object sender, EventArgs e)
    foreach (string arg in Environment.GetCommandLineArgs())


This code simply loops through the arguments returned by the Environment.GetCommandLineArgs method.

The first argument in the collection is always the fully-qualified name of the executing program. The rest of the collection holds any other arguments passed to the program.

This technique is interesting but even more interesting are the many ways you can send arguments to the program. For example, you can:

  • Set them in the IDE. Open the Project menu, select Properties (at the bottom), click the Debug tab, and enter the arguments in the “Command line arguments” text box. (This is mostly useful for testing.)
  • Execute the program at a command prompt (for example, the Run command or cmd.exe) and follow it with parameters
  • Drag and drop one or more files or folders onto the executable program.
  • Right-click and send a file or folder to the executable program added in the Send To menu (see my post Add items to the Send To menu).

The drag-and-drop and Send To methods give you a fairly easy way to make a program that processes files or directories. When it starts, the program can check its command line arguments. If there are any (besides the program’s name), it can process the files. If there are no arguments, it can display a user interface so the user can pick a file to process.

This is sort of how the example Search files in a directory hierarchy for a target string in C# works. When it starts, it checks its command-line arguments. If the progra mhas more than one argument, it places the second argument in the text box where you enter the search starting directory. That makes it easier to start a search. Simply drag a folder onto the executable program or send it to this program via the Send To menu.

This entry was posted in system and tagged , , , , , , , , , . Bookmark the permalink.

One Response to Get command line arguments in C#

  1. Rod Stephens says:

    Sorry about that. I’ve fixed it. Thanks for pointing this out!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.