【问题标题】:C# pass arguments with flags (/arg1 /arg2) to an exeC# 将带有标志 (/arg1 /arg2) 的参数传递给 exe
【发布时间】:2018-06-14 17:09:50
【问题描述】:

我可以使用一些帮助来确定如何将多个参数传递给我的可执行文件。我需要能够运行如下的可执行文件: myproject.exe -project ProjectName -jobs job1,job2

到目前为止,我的可执行文件被设计为运行另一个需要项目名称和单个作业名称的可执行文件,因此我的可执行文件将遍历给定的作业,以针对提供的每个作业名称运行另一个可执行文件。然后,我将根据给定的每个作业的其他可执行文件的输出做其他事情。例如,它列出了作业的状态,如果给定的任何作业未处于运行状态,我将让我的可执行文件启动提供的作业名称中的第一个作业。我可以将参数传递给我的可执行文件,但我不知道如何将作业名称与第一个参数分开。这是我目前所拥有的。

using System;
using System.Text;
using System.IO;
using System.Diagnostics;

public class Functions
{
        public static void runCommand(string executable, string execArguments)
    {
        Process process = new Process();
        process.StartInfo.FileName = executable;
        process.StartInfo.Arguments = execArguments; // Note the /c command (*)
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.Start();
        //* Read the output (or the error)
        string output = process.StandardOutput.ReadToEnd();
        Console.WriteLine(output);
        string err = process.StandardError.ReadToEnd();
        Console.WriteLine(err);
        process.WaitForExit();
    }
}

class MainClass
{
    static int Main(string[] args)
    {
        // Test if input arguments were supplied:
        if (args.Length == 0)
        {
            System.Console.WriteLine("Please enter a project and job name");
            System.Console.WriteLine("Usage: DSJobStatusMonitor <projectName>  <JobName1,JobName2>");
        }
    }
}

【问题讨论】:

  • 不要将参数传递为&lt;projectName&gt; &lt;Jobname1,Jobname2&gt;,而是传递为&lt;projectName&gt; &lt;Jobname1&gt; [&lt;Jobname2&gt; [...]]。它比用逗号分隔参数更容易解析,也更常见
  • 这就是我的想法,我不确定如何在 args 数组中的第二项开始 foreach 循环并继续处理每个剩余的参数?
  • 可能已经在这里回答了我自己的问题: inputArr.forEach((value, index) => { if (index

标签: c# arguments parameter-passing


【解决方案1】:

如果您将命令行参数更改为

<projectName> <Jobname1> [<Jobname2> [...]]

然后您可以遍历作业:

string projectname = args[0];
for(int i=1; i<args.Length; i++)
{
    string job = args[i];
    // do something with the job
}

如果您更喜欢将命令行参数保留为

<projectName> <Jobname1,Jobname2>

那么您需要在逗号处拆分并循环遍历作业:

string projectname = args[0];
var jobs = args[1].Split(',');
foreach(var job in jobs)
{
    // do something with the job
}

【讨论】:

    猜你喜欢
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    相关资源
    最近更新 更多