How to: Access Command-Line Arguments Using foreach (C# Programming Guide)
Another approach to iterating over the array is to use the foreach statement as shown in this example. The foreach statement can be used to iterate over an array, a .NET Framework collection class, or any class or struct that implements the IEnumerable interface.
Example
This example demonstrates how to print out the command line arguments using foreach.
class CommandLine2 { static void Main(string[] args) { System.Console.WriteLine("Number of command line parameters = {0}", args.Length); foreach (string s in args) { System.Console.WriteLine(s); } } }
Output
Number of command line parameters = 3 John Paul Mary | |
See Also
How to: Abstract Command-Line Arguments
Command-Line Arguments can be abstracted through a class to simplify access to them while providing default values for argument-configurable settings.
The following example shows an example class that provides default values for parameters.
public class ProgramArguments
{
private string displayText;
public string DisplayText
{
get { return displayText; }
}
public ProgramArguments()
{
displayText = "Hello World!";
}
public ProgramArguments(string[] args) : this()
{
for (int i=0; i<args.Length; i++)
{
string arg = args[i];
if (arg[0]!='-' && arg[0]!='/')
throw new ArgumentException(String.Concat("Invalid argument '", arg, "'"));
switch(arg.TrimStart('-','/'))
{
case "t":
displayText = TextArgument(args, ref i);
break;
}
}
}
private string TextArgument(string[] args, ref int i)
{
if (args.Length<i+2) throw new ArgumentException();
string value = args[++i];
if (value[0]=='-' || value[0]=='/') throw new ArgumentException();
return value;
}
}
public class Program
{
[STAThread]
public static void Main(string[] args)
{
ProgramArguments pa = new ProgramArguments(args);
Console.WriteLine(ps.DisplayText);
}
}
Output
// Program.exe
Hello World!
// Program.exe -t Hello
Hello
// Program.exe -t "Hello MSDN Wiki!"
Hello MSDN Wiki!
- 6/20/2006
- Richard Szalay
- 5/24/2007
- nameet.pai