如何使用C#/ Mono在Mac终端中以编程方式执行命令

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

我可以使用System.Diagnostics.Process打开新的终端窗口,但不能使用StandardInput.WriteLine向终端写入任何内容。

终端窗口打开,但没有命令写入终端窗口。

示例代码:

    var startInfo = new ProcessStartInfo {
        FileName = @"/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        RedirectStandardInput = true,
        UserName = System.Environment.UserName
    };

    using (var process = Process.Start (startInfo)) {
        process.StandardInput.WriteLine ("nuget"); // cannot get anything written to the terminal
    }
c# mono
1个回答
0
投票

我认为您可以使用以下代码:

    public static void ExecuteCommand(string command)
    {
        Process proc = new System.Diagnostics.Process ();
        proc.StartInfo.FileName = @"/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal";
        proc.StartInfo.Arguments = "-c \" " + command + " \"";
        proc.StartInfo.UseShellExecute = false; 
        proc.StartInfo.RedirectStandardOutput = true;
        proc.Start ();

        while (!proc.StandardOutput.EndOfStream) {
            Console.WriteLine (proc.StandardOutput.ReadLine ());
        }
    }

    public static void Main (string[] args)
    {
        ExecuteCommand("nuget");
    }
© www.soinside.com 2019 - 2024. All rights reserved.