转载 C#文件中GetCommandLineArgs()

本文介绍了C#中如何使用Environment类的GetCommandLineArgs()方法获取命令行参数。程序名被视为第一个参数,其余参数依次为第2、3等。通过示例代码展示了如何检查参数数量并进行文件复制操作。当参数少于3个时,会输出格式化的错误信息。此方法有助于获取程序的实际执行名称,确保‘用法’消息中的程序名正确,即使程序被重命名。

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被重命名后 提供的用法信息仍然是正确的.

转载于:https://www.cnblogs.com/playingyin/archive/2012/10/30/2746690.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值