【问题标题】:Using single quote in C# Process.Start argument在 C# Process.Start 参数中使用单引号
【发布时间】:2019-07-22 22:31:35
【问题描述】:

我需要使用包含单引号 ' 的参数从 .Net Core 执行 Linux 命令行程序

两个例子:

dpkg-query -W -f=' ${db:Status-Status} ' mariadb*

virsh qemu-agent-command SRV01 '{"execute":"guest-ping"}' 

在 C# 中:

Process proc = new System.Diagnostics.Process();
ProcessStartInfo pi = new ProcessStartInfo("dpkg-query");
pi.Arguments = "-W -f=' ${db:Status-Status} ' mariadb*";
proc.StartInfo = pi;
proc.Start();

错误信息示例:'''''''''''''''''''dpkg-query: no packages found matching ${db:Status-Status} dpkg-query: no packages found matching '

我正在调用大约 30 个带有参数的不同程序,没有任何问题。只有单引号有问题

还尝试使用ProcessStartInfo.ArgumentList 和许多基本的逃生技巧,但没有成功。

【问题讨论】:

  • 我想是的...根据 dpkg-query 手册第 122 行:syntax “${field[;width]}”
  • 调试值为-W -f=' ${db:Status-Status} ' mariadb*我可以在控制台看到程序的错误信息。它们在Linux shell中执行良好
  • @RobertBaron:它是从在 Linux 上运行的 .Net Core 控制台程序调用的(安装了 .Net Core 运行时)。
  • @mjwills:该程序以 root 身份运行,我所在的工作文件夹无关紧要。附加信息:所有其他不带单引号的命令都可以正常工作
  • 错误示例:'''''''''''''''''''dpkg-query: no packages found matching ${db:Status-Status} dpkg-query: no packages found matching ' 。但这当然取决于程序和论据。底线是当引号被解析时会发生一些事情。我认为这是一些 C++ 解析问题正如我所说尝试了许多不同的转义解决方案。

标签: c# linux .net-core process parameter-passing


【解决方案1】:

解决方案:

using System;
using System.Diagnostics;

namespace Exe
{
    class Program
    {
        static void Main(string[] args)
        {
            Process proc = new System.Diagnostics.Process();

            //In the Linux shell: dpkg-query -W -f=' ${db:Status-Status} ' mariadb*:
            ProcessStartInfo pi = new ProcessStartInfo("dpkg-query");
            pi.ArgumentList.Add("-W");
            pi.ArgumentList.Add("-f= ${db:Status-Status} ");
            pi.ArgumentList.Add("mariadb*");

            pi.UseShellExecute = false;
            proc.StartInfo = pi;
            proc.Start();
            do { System.Threading.Thread.Sleep(50); } while (proc.HasExited == false);
            Environment.Exit(0);
        }
    }
}

还有另一个命令示例:

....
//In the Linux shell: virsh qemu-agent-command SRV04 '{"execute":"guest-ping"}'
ProcessStartInfo pi = new ProcessStartInfo("virsh");
pi.ArgumentList.Add("qemu-agent-command");
pi.ArgumentList.Add("SRV03");
pi.ArgumentList.Add("{\"execute\":\"guest-ping\"}");
....

TSlivedejnm2 的帮助下解决了这个github.com 胎面:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2011-06-11
    • 1970-01-01
    • 2016-06-15
    • 2017-05-07
    • 2011-03-17
    相关资源
    最近更新 更多