.net控制台程序Program args参数解析

一直很有疑问在控制台程序的Main函数中为什么会有个string[] args的参数,又没有什么用。

static void Main(string[] args)
{
}

这几天需要将一个控制台程序改造为既能作为exe双击运行,又能作为windows服务运行,然后开始研究到这个参数了。经过查询资料才发现这个参数其实有很大的作用。它是用来接收我们的启动参数的,比如我们有时候启动软件在敲命令时加上什么s,r什么的,就可以认为是启动参数了。例如图片中的s参数在启动这个exe时里面的args就会有值了。

image

然后在代码中我们就可以进行判断该软件是以何种方式运行了。

static void Main(string[] args)
{
    if (args.Length > 0 && args[0] == "s")
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
          new EngineOnWinService()
        };
        ServiceBase.Run(ServicesToRun);
    }
    else
    {
        EngineOnHandler.EngineOnDataHandler();
    }
}

 

posted @ 2016-04-14 10:43  jiewus  阅读(1184)  评论(0编辑  收藏  举报