Csharp/CSharp Tutorial/Development/Command Line

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Display all command-line information

<source lang="csharp">using System;

class MainClass {

 public static void Main(string[] args) { 
   Console.WriteLine("There are " + args.Length + 
                      " command-line arguments."); 

   Console.WriteLine("They are: "); 
   for(int i=0; i < args.Length; i++)  
     Console.WriteLine(args[i]);  
 }  

}</source>

There are 0 command-line arguments.
They are:

Iterate over command-line arguments and print them out

<source lang="csharp">using System; class MainClass {

   public static void Main(string[] args)
   {
       for (int arg = 0; arg < args.Length; arg++){
           Console.WriteLine("Arg {0}: {1}", arg, args[arg]);    
       }
       
   }

}</source>

Read user input from command line and change the console color

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text;

 class Program
 {
   static void Main(string[] args)
   {
     Console.Write("Please enter your name: ");
     string userName = Console.ReadLine();
     Console.Write("Please enter your age: ");
     string userAge = Console.ReadLine();
     ConsoleColor prevColor = Console.ForegroundColor;
     Console.ForegroundColor = ConsoleColor.Yellow;
     Console.WriteLine("Hello {0}!  You are {1} years old.",userName, userAge);
     Console.ForegroundColor = prevColor;
   }
 }</source>

See if arguments are present

<source lang="csharp">using System;

class Cipher {

 public static int Main(string[] args) {   

   if(args.Length < 2) { 
     Console.WriteLine("Usage: encode/decode word1 [word2...wordN]"); 
     return 1; // return failure code 
   } 

   // if args present, first arg must be encode or decode 
   if(args[0] != "encode" & args[0] != "decode") { 
     Console.WriteLine("First arg must be encode or decode."); 
     return 1; // return failure code 
   } 

   for(int n=1; n < args.Length; n++) { 
     for(int i=0; i < args[n].Length; i++) { 
       if(args[0] == "encode") 
         Console.Write("encode"); 
       else  
         Console.Write("Decode"); 
     } 
     Console.Write(" "); 
   } 

   Console.WriteLine(); 

   return 0; 
 } 

}</source>