首页 文章

使用参数从.NetCore运行bash命令

提问于
浏览
5

我试图从另一个运行一个.NetCore程序 .

ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "sh";
        psi.Arguments = "-c dotnet /home/myuser/PublishOutput/myprogram.dll";
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;

        Process proc = new Process
        {
            StartInfo = psi
        };


        proc.Start();

        string error = proc.StandardError.ReadToEnd();

        if (!string.IsNullOrEmpty(error))
            return "error: " + error;

        string output = proc.StandardOutput.ReadToEnd();

        proc.WaitForExit();

        return output;

作为输出我得到:

Microsoft .NET Core共享框架主机版本:1.1.0 Build:928f77c4bc3f49d892459992fb6e1d5542cb5e86用法:dotnet [common-options] [[options] path-to-application]公共选项: - help显示.NET Core共享框架主机帮助 . --version显示.NET Core共享框架主机版本 . 选项: - fx-version用于运行应用程序的已安装Shared Framework的版本 . --additionalprobingpath包含要探测的探测策略和程序集的路径 . 应用程序的路径:.NET Core托管应用程序的路径,要执行的dll或exe文件 . 如果要调试Shared Framework Host,请在环境中将“COREHOST_TRACE”设置为“1” . 要开始开发.NET Core应用程序,请从以下位置安装SDK:http://go.microsoft.com/fwlink/?LinkID = 798306&clcid = 0x409

所以我似乎非常喜欢运行命令dotnet而没有dll路径参数 .

2 回答

  • 0

    您需要将参数转义为 -c ,以便它是一个参数:

    psi.Arguments = "-c \"dotnet /home/myuser/PublishOutput/myprogram.dll\"";
    
  • 3

    我改变了一些东西,使消息可以输出同步

    using System;
    using System.Diagnostics;
    using System.Threading.Tasks;
    
    namespace ExecuteCommandX
    {
     /// <summary>
    ///  sample by linkanyway@gmail.com
    /// </summary>
    /// <param name="args"></param>
    internal static class Program
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        // ReSharper disable once UnusedParameter.Local
        private static void Main(string[] args)
        {
            var psi = new ProcessStartInfo
            {
                FileName = "ping",
                Arguments = "-c 3 8.8.8.8",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };
    
            var proc = new Process
            {
                StartInfo = psi
            };
    
            proc.Start();
    
    
    
            Task.WaitAll(Task.Run(() =>
            {
                while (!proc.StandardOutput.EndOfStream)
                {
                    var line = proc.StandardOutput.ReadLine();
                    Console.WriteLine(line);
                }
            }), Task.Run(() =>
            {
                while (!proc.StandardError.EndOfStream)
                {
                    var line = proc.StandardError.ReadLine();
                    Console.WriteLine(line);
                }
            }));
    
    
            proc.WaitForExit();
            Console.WriteLine(proc.ExitCode);
        }
    }
    

    }

相关问题