【问题标题】:C# how can you get output of an other batch file?C#如何获取其他批处理文件的输出?
【发布时间】:2008-10-11 14:29:40
【问题描述】:

我必须使用其他应用程序(控制台)将一些参数传递给该程序,并在我的 C# 程序中获取该程序的输出。我不想看到控制台(对用户来说都是不可见的)。我该怎么做?

【问题讨论】:

    标签: c# io


    【解决方案1】:
    Process myProcess = new Process();
    ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("YOUPROGRAM_CONSOLE.exe" );
    myProcessStartInfo.UseShellExecute = false;
    myProcessStartInfo.RedirectStandardOutput = true;
    myProcess.StartInfo = myProcessStartInfo;
    myProcess.Start();
    
    StreamReader myStreamReader = myProcess.StandardOutput;
    string myString = myStreamReader.ReadLine();
    Console.WriteLine(myString);
    myProcess.Close();
    

    来源:MSDN

    编辑: 如果您需要获取错误消息,则需要使用异步操作。您可以使用异步读取操作来避免这些依赖关系及其潜在的死锁。或者,您可以通过创建两个线程并在单独的线程上读取每个流的输出来避免死锁情况。

    【讨论】:

    • 您还需要启用“RedirectStandardError”,并读取该流,以防您的子进程生成错误消息。
    • 我添加了一些信息。在 MSDN 中,它说它需要多个线程来避免死锁。
    • 如果你真的想输出到控制台,你可以使用Console.SetIn(myProcess.StandardOutput);而不是额外的StreamReader-Object。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 2019-01-08
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多