Skip to main content
 首页 » 编程设计

C# 分隔参数并将其传递给 Process.Start() 方法

2024年02月05日14zhoujg

我需要向我的 concole 应用程序传递几个参数:

1 项目名称

2 版本名称

3 部署环境名称

4 一些 bool 值

5 整数数组

据我所知,我需要运行以下代码:

  string myParams = "Test proj name " + "3.22.652.965863 " + "QA " + "true " + "463841"; 
        //string cParams = "true "; 
        var proc = System.Diagnostics.Process.Start(@"c:\\ MyFolder\bin\Debug\MyApp.exe", myParams); 

鉴于 MyExe.exe 入口点具有此代码:

static void Main(string[] args) 
    { 
 
        //Console.WriteLine(Convert.ToBoolean(args[0])); 
 
        string projectName = null; 
        string buildNumber = null; 
        string deploymentEnvironmentName = null; 
        bool shouldResolve = false; 
        List<int> ids = new List<int>(); 
 
 
        if (args.Length >= 5) 
        { 
            for (int i = 0; i < args.Length; i++) 
            { 
                if (i == 0) 
                { 
                    Console.WriteLine($"Arg: {i} is {args[i]}"); 
                    projectName = args[i]; 
                } 
                if (i == 1) 
                { 
                    Console.WriteLine($"Arg: {i} is {args[i]}"); 
                    buildNumber = args[i]; 
                } 
                if (i == 2) 
                { 
                    Console.WriteLine($"Arg: {i} is {args[i]}"); 
                    deploymentEnvironmentName = args[i]; 
                } 
                if (i == 3) 
                { 
                    Console.WriteLine($"Arg: {i} is {args[i]}"); 
                    Console.WriteLine($"Boolean convertion: {args[i]}"); 
                    shouldResolve = Convert.ToBoolean(args[i]); 
                } 
                if (i > 3) 
                { 
                    ids.Add(Convert.ToInt32(args[i])); 
                } 
            } 
            MyService.MyMethod(ids, projectName, buildNumber, deploymentEnvironmentName, shouldResolve); 
        } 
        else 
        { 
            throw new Exception("You should define arguments only in following order: Project Name, Build Number, Deployment Environment Name and Array of your Change Sets"); 
        } 
 
        Console.ReadLine(); 
    } 

我事先不知道我要有多少个整数,但我需要提前知道其他参数的顺序。 但是我的问题是 System.Diagnostics.Process.Start 方法通过空格分隔参数。这意味着我的第一个参数“Test proj name”不会被转换为一个参数,而是会被解析为“Test”、“proj”和“name”。它弄乱了我的代码,我不能提前指望参数的顺序。 我该如何解决? 也许我可以定义自己的分隔符并忽略空格作为分隔符? 我将不胜感激任何帮助或建议。

请您参考如下方法:

您应该能够通过将参数括在双引号中来解决此问题:

string myParams = "\"Test proj name\" " + "3.22.652.965863 " + "QA " + "true " + "463841"; 

来自documentation :

A single argument that includes spaces must be surrounded by quotation marks, but those quotation marks are not carried through to the target application.

即您的应用程序将收到不带引号的 Test proj name 字符串。