【问题标题】:Run winform application with terminal command, with the configuration xml file given as command argument使用终端命令运行 winform 应用程序,并将配置 xml 文件作为命令参数给出
【发布时间】:2017-07-04 07:42:28
【问题描述】:

批量测试需要从终端调用现有的 winforms 应用程序(例如 MyApp.exe),使用存储在与 .exe 相同目录的 .xml 文件中的配置(例如 MyAppConfig.xml)。为了能够从终端调用start /realtime c:\MyApp.exe /config="MyAppConfig.xml",我应该对应用程序进行哪些更改。谁能指出我如何实现此功能的正确方向?帮助表示赞赏。

【问题讨论】:

    标签: c# xml winforms command-line


    【解决方案1】:

    在您的应用程序的Program.cs 文件中,您将找到您的应用程序入口点Main() 方法。更改其签名并添加将保存参数的string 数组。然后,检查参数并实现您的逻辑。

    类似这样的:

    static void Main(string[] startArgs)
    {
        if (startArgs.Length == 0)
        {
            //show messagebox stating that there's no parameters or something else
        }
        else
        {
            var configArg = startArgs.FirstOrDefault(s => s.StartsWith("config"));
            if (configArg == null)
            {
                //config parameter is missing
            }
            else
            {
                string xml = configArg.Split('=')[1];
                //xml holds your path to your xml file. 
                //Now you can pass it to form, or load it here
    
                //XmlDocument doc = new XmlDocument();
                //doc.Load(xml);
                //etc...
            }
    
        }
    
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
    

    如果你打算有多个命令行参数,你应该寻找NET CLI library,它是 apache commons cli API 的 .net 端口,用于解析命令行参数...

    【讨论】:

    • 非常感谢,非常完整和干净的解释!
    • @MiroslavRadojević 很高兴我能提供帮助。斯雷特诺! ;)
    【解决方案2】:

    在构建控制台或表单应用程序时,Main 方法通常用作代码的入口点。它接受一个字符串数组作为从 CLI 传递下来的参数。

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

    所以运行program.exe FOO BAR 会导致:

    Argument #0 = FOO 
    Argument #1 = BAR
    

    您也可以使用program.exe config="MyAppConfig.xml" 表示法使参数顺序无关,但您必须自己进行一些解析。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 2015-04-14
      • 2018-06-22
      相关资源
      最近更新 更多