我需要从.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和许多基本的转义技巧,但没有成功。

最佳答案

解决方案:

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胎面:-)

10-06 05:02
查看更多