C# 字符串数组连接到转义字符串(如 ArgumentList)?

问题描述 投票:0回答:1

我不经常使用C#,但是,我需要修改一些代码,其中使用:

  Process new_process = new Process();
  new_process.StartInfo.FileName = "mytool.exe";

现在,我必须拨打电话,但是命令行选项列表相当大,其中一些包含空格,需要加引号。

所以,我看到存在这个:https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.argumentlist?view=net-7.0#system-diagnostics-processstartinfo-参数列表

...
// or if you prefer collection property initializer syntax:

var info = new System.Diagnostics.ProcessStartInfo("cmd.exe")
{
    ArgumentList = {
        "/c",
        "dir",
        @"C:\Program Files\dotnet"
    }
};

// The corresponding assignment to the Arguments property is:

var info = new System.Diagnostics.ProcessStartInfo("cmd.exe")
{
    Arguments = "/c dir \"C:\\Program Files\\dotnet\""
};

我很想使用 ArgumentList - 问题是,当我在 Visual Studio 中尝试在

new_process.StartInfo.
上自动完成时,我只得到
Arguments
,没有
ArgumentList
;我认为我正在尝试修改这个应用程序,目标是 .NET 4.6 - 上面的页面说的是 ArgumentList,它适用于:

.NET Core 2.1、Core 2.2、Core 3.0、Core 3.1、5、6、7、8

所以,我想我在这里使用ArgumentList(不是我的应用程序,所以我真的无法决定更改核心版本,如果这确实是问题)。

因此,如果是这种情况,C# 中是否存在某种类,它本质上是字符串的列表/数组容器,并且可能具有“join_quoted”方法或其他方法,以便它将数组元素与空格,并引用那些需要引用的元素 - 所以对于

  • 输入数组
    {"/c", "dir", @"C:\Program Files\dotnet"}
    ,我可以自动获取
  • 输出连接了引号字符串,这里是
    "/c dir \"C:\\Program Files\\dotnet\""

...?

c# arrays string escaping quoting
1个回答
0
投票

我在 .NET 4.6 中遇到了完全相同的问题,正如@NineBerry 评论提供的链接中所述,解析规则非常复杂。我最终创建了自己的类,改编了来自 dotnet/runtime 存储库的此方法的逻辑。

该方法在这个测试用例中进行了演示,它也应该符合您的需求。

© www.soinside.com 2019 - 2024. All rights reserved.