C#防止已启动的应用程序在控制台中写入

C#防止已启动的应用程序在控制台中写入,c#,.net-core,console,C#,.net Core,Console,我有一个应用程序可以启动另一个应用程序。另一个应用程序在控制台中打印几行,但没有人需要这个输出,它在我自己的输出之间打印它的输出。我怎样才能防止其他应用程序将其内容打印到我的控制台? 我尝试在true和false上运行ProcessStartInfo.UseShellExecutive,也尝试在启动前将控制台输出更改为MemoryStream,但由于我需要控制台,我不得不将输出更改回原来的状态,看起来其他应用也将输入更改回原来的状态 Process serverprocess = new Pro

我有一个应用程序可以启动另一个应用程序。另一个应用程序在控制台中打印几行,但没有人需要这个输出,它在我自己的输出之间打印它的输出。我怎样才能防止其他应用程序将其内容打印到我的控制台? 我尝试在
true
false
上运行
ProcessStartInfo.UseShellExecutive
,也尝试在启动前将控制台输出更改为MemoryStream,但由于我需要控制台,我不得不将输出更改回原来的状态,看起来其他应用也将输入更改回原来的状态

Process serverprocess = new Process();
serverprocess.StartInfo.FileName = Path.GetFileName(serverpath);
serverprocess.StartInfo.Arguments = launch;
serverprocess.StartInfo.UseShellExecute = false;
serverprocess.StartInfo.RedirectStandardOutput = true;
serverprocess.Start();

在代码中,确保您正在重新定向
StandardOutput
StandardError
,这样“第三方应用”写入的所有内容都将被捕获到这些流中

我已经编写了一个小的助手类来帮助实现这一点

你可以用like

//Launching excel.exe with /safe as arg
var excelExample1 = @"""C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE"" /safe";

LaunchCMD.Invoke(excelExample1);

//To get its output, if any
var getOutput = LaunchCMD.Output;
LaunchCMD助手类

class LaunchCMD
{


    public static string Output
    {
        get; set;
    } = "";




    public static void Invoke(string command, bool waitTillExit = false, bool closeOutputWindow = false)
    {

        ProcessStartInfo ProcessInfo;
        Process Process = new Process();


        ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + command);


        ProcessInfo.CreateNoWindow = false;
        ProcessInfo.UseShellExecute = false;
        ProcessInfo.RedirectStandardOutput = true;
        ProcessInfo.RedirectStandardError = true;
        Process.EnableRaisingEvents = true;

        Process = Process.Start(ProcessInfo);


        Process.ErrorDataReceived += ConsoleDataReceived;
        Process.OutputDataReceived += ConsoleDataReceived;


        Process.BeginOutputReadLine();
        Process.BeginErrorReadLine();




        if (waitTillExit == true)
        {


            Process.WaitForExit();
        }
        if (closeOutputWindow == true)
        {
            Process.CloseMainWindow();
        }


        Process.Close();
        System.Threading.Thread.Sleep(1000);
        Output.ToString();


    }


    private static void ConsoleDataReceived(object sender, DataReceivedEventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        if (e.Data != null)
        {
            Output = Output + e.Data;
        }
    }


}

您是如何将子进程stdout重定向到memorystream的?至少显示代码的这一部分。重定向(类似于
>nul
)也可以工作。添加。。您:)这是否适用:(将
RedirectStandardOutput
设置为true,只是没有将任何处理程序附加到
OutputDataReceived
)?我不确定是否理解正确,但我添加了重定向,没有向OutputDataReceived添加任何内容,但它仍然显示在我的控制台中:((将post更改为当前代码)可能子进程写入stderr而不是stdout。重定向错误输出,还有一个单独的属性。相关:我必须重定向流,但我不需要为这些流附加任何处理程序,我只是忘记了ARK服务器也可能使用stderr而不是stdout,所以我只将stdout重定向为nothing:/