转载 C#文件中GetCommandLineArgs()

C#文件中GetCommandLineArgs()  

解释:该函数使用Environment类方法获取命令行参数;

使用该函数时 程序名被视为第1参数,命令行中的其他值依次被视为第2 3...个参数.

通过一个例子来讲解文件和该函数的用法:

using System;

using System.IO;

class myApp

{

   public static void Main()

   {

   string [] CLA = Enviroment.GetCommandLineArgs();            //获取命令 第一个为文件名

   if(CLA.Length<3)                                                                  //判断获取的字符数组个数是否小于3

    {

     Console.WriteLine("Format:{0} orig-file new-file",CLA[0]);

    }

   else

  {

   string origfile = CLA[1];

   string newfile = CLA[2];

   Console.WriteLine("Copy. . . .");

   try

  {

     File.Copy(origfile,newfile);                                                             //尝试操作新文件拷贝旧文件 或引发异常

   }

catch (System.IO.FileNotFounfException)

{

Console.WriteLine("\n{0} does not exist!",origfile);

return;

}

catch (System.IO.IOException)

{

Console.WriteLine("\n{0} already exists!",newfile);

}

catch (Exception e)

{

Console.WriteLine("\nAn expection was thrown trying to copy file.");

Console.WriteLine;

return;

}

Console.WriteLine("...Done");

}

}

}

GetCommandLineArgs()这个函数需要三个值来获取程序名,原来的文件名 和新创建的程序名 如果少于三个值 则

将返回格式 文件名 旧文件 新文件这样的格式.

用该函数的价值在于 提供了用户实际执行程序的名称 这样在"用法"消息包含的讲师实际的程序名而不是代码名.

这样做饿好处 当程序filecopu被重命名后 提供的用法信息仍然是正确的.

posted on 2012-10-30 17:18  ltyfat  阅读(682)  评论(0编辑  收藏  举报