代码之家  ›  专栏  ›  技术社区  ›  Legends

使用Scult.Cycess进程调用EXE防止输出流中的噪声数据

  •  0
  • Legends  · 技术社区  · 6 年前

    我要使用以下npm命令获取包的版本号:

    npm show webpack version
    

    在我的 proc_OutputDataReceived 事件处理程序我预先获取噪声数据, 您可以在事件处理程序的注释中看到输出。

    是否可以防止噪声数据并只获取版本号,或者我必须分析输出?

     public static string getVersionInfo()
    {
    
        var psi = new ProcessStartInfo
        {       
            FileName = "cmd",
            RedirectStandardInput = true,
            UseShellExecute= false,
            WorkingDirectory = @"C:\Users\...",
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
    
        var proc = Process.Start(psi);
    
        proc.OutputDataReceived += proc_OutputDataReceived;
        proc.ErrorDataReceived += Proc_ErrorDataReceived;
        proc.BeginOutputReadLine();
        proc.StandardInput.WriteLine("npm show webpack version & exit"); 
        proc.WaitForExit();
    
    }
    
    static void proc_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
    {
        Debug.WriteLine(e.Data);
        // prints:
        // "Microsoft Windows [Version 10.0.17134.112]"
        // "(c) 2018 Microsoft Corporation. All rights reserved."
        // ""
        // "C:\\Users...\\workingFolder>npm show webpack version & exit"
        // "4.12.0"   <-- THIS IS THE DESIRED RESULT !!!
        // null
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Lasse V. Karlsen    6 年前

    生成一个shell,然后向它发送命令,这将从shell程序中打印出信息以及要执行的命令。

    解决方法是问shell程序, cmd ,以便直接执行程序。

    只需将程序传递给 cmd.exe 作为参数的可执行文件,前缀为 /C “执行和退出”。

    下面是您需要做的更改:

    1. 添加 Arguments
    2. 去除 RedirectStandardInput
    3. 不要向shell发送命令

    现在你应该:

    var psi = new ProcessStartInfo
    {       
        FileName = "cmd",
        Arguments = "/C npm show webpack version",
        UseShellExecute= false,
        WorkingDirectory = @"C:\Users\...",
        RedirectStandardOutput = true,
        RedirectStandardError = true
    };
    

    然后删除向shell发送命令的行:

    proc.StandardInput.WriteLine("npm show webpack version & exit");  // delete
    

    应该就是这样。