如何在C#我做控制台输出在多个流一次? [英] How do I output console to multiple streams at once in C#?

查看:142
本文介绍了如何在C#我做控制台输出在多个流一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,它的控制台输出,并将其写入到一个日志文件,但它不再显示在控制台窗口。有没有一种方法,以保持它的窗口,但其写入日志文件中呢?

I have a program that takes the Console output and writes it to a logfile, however it no longer shows up in the console window. Is there a way to keep it in the window but write it to the log file as well?

更新:

appLogStream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read);
TextWriter logtxtWriter = Console.Out;
logstrmWriter = new StreamWriter(appLogStream);
if(!console) Console.SetOut(logstrmWriter);
logstrmWriter.AutoFlush = true;
Console.WriteLine("Started at " + DateTime.Now);

控制台是在类中的常数集。它主要是告诉它是否是使用控制台窗口或不(readline的不叫,等等,如果不是在控制台)。

console is a constant set in the class. It basically tells it whether it is using the console window or not (readline is not called, etc, if not in console).

那么,有没有办法写控制台和文件?

So is there a way to write to both the console and the file?

推荐答案

您可以简单地读取数据流记录它,并把它打印出来。

You could simply read that stream log it and print it out.

如果您指定的输出流outfile中的InputStream的,如果你读了内容的缓冲区应该是一个更容易一些,这可能是一个有点困难这取决于一点点在你的code。

It depends a little on your code if you assign the output stream to the inputstream of the outfile this could be a little harder if you read the content to a buffer that should be a little easier.

关于您的更新,我建议你交换所有控制台用自定义的日志记录功能,例如MyLogger的一个实例(低于code)。其中的输出写入到控制台和日志文件。

About your update I would suggest that you exchange all Console with a custom logging function e.g. a instance of MyLogger (code below) . Which writes your output to the console and to your log file.

class MyLogger {
    private FileStream appLogStream;

    public MyLogger() {
        appLogStream = new FileStream(logFile, FileMode.Append, FileAccess.Write,
                                      FileShare.Read);
        appLogStream.WriteLine("Started at " + DateTime.Now);
    }

    public Write(string msg) {
        Console.Write(msg);
        appLogStream.Write(msg);
    }

    public WriteLine(string msg) {
        Console.WriteLine(msg);
        appLogStream.WriteLine(msg);
    }
}

这篇关于如何在C#我做控制台输出在多个流一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆