Get a program's command line arguments in C#

One method to do this is to override the Main method and give it a parameter that is a string array.

static void Main(string[] args)
{
foreach (string arg in args)
{
lstArguments.Items.Add(arg);
}
}

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.

Form1_Load(object sender, EventArgs e)
{
foreach (string arg in Environment.GetCommandLineArgs())
{
lstArguments.Items.Add(arg);
}
}

The first argument is always the fully-qualified name of the executing program.

This technique is interesting but even more interesting are the ways you can send arguments to the program. 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" TextBox. (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 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, it 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 how the Search files in a directory hierarchy for a target string in C# example works.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.