Loading...
 
JoiWiki » Developer » .Net » .Net Snippets » CSharp Loop Through Command Line Arguments CSharp Loop Through Command Line Arguments

CSharp Loop Through Command Line Arguments

Loop Through Command Line Arguments

So command line arguments are great, you can put information into a shortcut (or from the command line) to be passed as parameters to the target assembly and that assembly can catch it!

 

I'll come back to this article later to put more information in but here's some c# to catch the parameters, loop through them and show them in a messagebox - use this wisely as you will only get string params through and will need to cast anything out to any other datatypes as required. The only issue with this is that if you are going to use this manually you will need knowledge of which parameters go where and how they are used. 

 

 

private void ShowArgs()
{
    // Let's go grab our parameters
    String[] Arguments = Environment.GetCommandLineArgs();
    foreach (string Arg in Arguments)
    {
        MessageBox.Show(Arg, "Here's an argument..");
    }
}

 

it's worth noting however that the first argument is the executable filename so you might want to insulate against that with something like the following which was taken from something I wrote to test command line arguments being sent to an exe from different sources:

 

public static bool TestArguments()
{
	bool HasArgs = false;

	// Let's go grab our parameters
	String[] Arguments = Environment.GetCommandLineArgs();

	if (Arguments.Length > 1)
	{
		for (int i = 1; i <= Arguments.Length; i++)
		{
			MessageBox.Show(Arguments[i], "Here's an argument..");
			HasArgs = true;
		}
	}

	return HasArgs;
}

 

 

Created by JBaker. Last Modification: Thursday June 20, 2019 11:44:25 BST by JBaker.

Developer