【问题标题】:Console redirection of the current process in MonoMono中当前进程的控制台重定向
【发布时间】:2010-05-20 21:35:35
【问题描述】:

我正在尝试将 C#/Mono 应用程序的控制台输出重定向到 gtk# 文本视图。这里有无数的答案来解释如何将命令的输出重定向到任何可以想象的输出设备。但是,我正在尝试对当前流程做同样的事情。最初该应用程序被设计为命令行,知道我想要一个显示所有输出的文本视图。这是我现在拥有的:


class Program
{
     Main(string[] args)
     {
           Program prog = new Program();
           Process proc = Process.GetCurrentProcess();
           proc.StartInfo.RedirectStandardOutput =  true;
           proc.StartInfo.RedirectStandardError = true;
           proc.EnableRaisingEvents = true;
           proc.ErrorDataReceived += prog.DataReceived;
           proc.OutputDataReceived += prog.DataReceived;
           proc.BeginErrorReadLine();
           proc.BeginOutputReadLine();
     }
     void DataReceived(object sender, DataReceivedEventArgs e)
     {
           _MainWindow.SendData(e.Data);
     }
}

这是正确的方法吗?现在我在调用BeginErrorReadLine() 方法时收到以下异常。例外是: Standard Error Can not be redirected。我不知道问题是否只是 Process/Mono 的问题,或者我只是做错了什么。

【问题讨论】:

    标签: c# mono monodevelop gtk#


    【解决方案1】:

    我相信你不能在进程开始后重定向标准输出(这是当前进程的情况)。

    看看Console.SetOut Method

    将 Out 属性设置为指定的 TextWriter 对象。

    例子:

    FileStream fs = new FileStream("Test.txt", FileMode.Create);
    StreamWriter sw = new StreamWriter(fs);
    
    Console.SetOut(sw);
    Console.WriteLine("Hello World");
    

    这会将“Hello World”的输出重定向到文本文件。

    您需要实现自己的 TextWriter,将所有文本写入 gtk# textview。


    或者,由于它是您的程序,您可以将所有对 Console.Write/WriteLine 的调用替换为自定义方法,该方法将字符串写入 gtk# textview 或控制台,具体取决于程序参数:

    abstract class Stdout
    {
        public static readonly Stdout Instance = // ...
    
        public abstract void WriteLine(string s);
    
        private class Console : Stdout
        {
            public override void WriteLine(string s)
            {
                Console.WriteLine(s);
            }
        }
    
        private class Gui : Stdout
        {
            public override void WriteLine(string s)
            {
                // append to gtk# textview
            }
        }
    }
    

    【讨论】:

    • 我以前看过这个,但是我使用了writer,然后我只能批量获取控制台消息,对吧?我需要的是每条消息都独立发送到文本视图。
    【解决方案2】:

    您可能对使用 Vte 感兴趣。 Vte 是 gnome-terminal 使用的终端仿真小部件。它具有 gnome-sharp 中包含的 C# 绑定。

    您实际上可以告诉它使用一种方法启动一个进程。 Here is the documentation for the Vte.Terminal class。具体看ForkCommand()方法。

    【讨论】:

      猜你喜欢
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多