본문 바로가기

Software/C#.Net

Processing Command-Line Arguments

for Loop version

static int Main(string[] args)
{
...
  // Process any incoming args.
  for(int i = 0; i < args.Length; i++)
    Console.WriteLine("Arg: {0}", args[i])
 
  Console.ReadLine();
  return -1;
}

Foreach Version

// Notice you have no need to check the size of the array when using "foreach".
static int Main(string[] args)
{
...
  // Process any incoming args using foreach.
  foreach(string arg in args)
    Console.WriteLine("Arg: {0}", arg);
 
  Console.ReadLine();
  return -1;
}

GetCommandLineArgs() Version
namespace : System.Environment
return value: an array of strings
first index : identifies the name of the application itself

static int Main(string[] args) 
{ 
... 
  // Get arguments using System.Environment. 
  string[] theArgs = Environment.GetCommandLineArgs(); 
  foreach(string arg in theArgs) 
    Console.WriteLine("Arg: {0}", arg); 
 
  Console.ReadLine(); 
  return -1; 
} 

An Interesting Aside: Some Additional Members of the System.Environment Class

// Print out the drives on this machine, and other interesting details. 
  foreach (string drive in Environment.GetLogicalDrives()) 
    Console.WriteLine("Drive: {0}", drive); 
 
  Console.WriteLine("OS: {0}", Environment.OSVersion); 
  Console.WriteLine("Number of processors: {0}",  Environment.ProcessorCount); 
  Console.WriteLine(".NET Version: {0}",     Environment.Version);
System.Environment
---------------------------------------------------------------------------------------------
Property                      Meaning in Life
---------------------------------------------------------------------------------------------
ExitCode                      Gets or sets the exit code for the application.
MachineName               Gets the name of the current machine. 
NewLine                       Gets the newline symbol for the current environment. 
StackTrace                   Gets the current stack trace information for the application.
SystemDirectory           Returns the full path to the system directory. 
UserName                    Returns the name of the user that started this application. 
---------------------------------------------------------------------------------------------