[英]Change textwriter to write to console
我具有要转换的现有功能,因此它将logMessage打印到控制台。 最初,这被用作cmd line应用程序,我已将其转换为C#中的Windows窗体应用程序。 我如何更改输出流,以便将其写入文件或控制台?
/// <summary>
/// Prints a log message to stderr.
/// </summary>
public static void logMessage(String format, params Object[] args)
{ //Change output stream if desired
TextWriter logStream = Console.Error;
Console.OutputEncoding = System.Text.Encoding.UTF8;
logStream.WriteLine(logTime() + " " + format, args);
}
要写入文件,可以将Console.Error
替换为StreamWriter
对象。 但是,您可能需要围绕此方法添加一些锁定,但我不确定这将如何处理来自多个线程写入文件的并发消息。
我想我现在明白控制台的意思了……您是说一些文本框? 如果是,那么您可以执行以下操作:
public class TextBoxWriter : TextWriter
{
TextBox _textBox = null;
public TextBoxWriter(TextBox textBox)
{
_textBox = textBox;
}
private void AppendText(string message)
{
_textBox.AppendText(message);
_textBox.AppendText(Environment.NewLine);
}
public override void Write(string message)
{
base.Write(message);
if (_textBox.InvokeRequired)
_textBox.Invoke(new Action<string>((msg) => AppendText(msg)), message);
else
AppendText(message);
}
public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
接着
TextWriter logStream = new TextBoxWriter(yourTextBox);
如果您想写入文件,则可能会出现类似Joe的建议,但请记住要同步该部分,除非您确定只通过一个线程访问它。
替换此行
logStream.WriteLine(logTime() + " " + format, args);
用这条线
Console.WriteLine(logTime() + " " + format, args);
我没有测试它,但是它应该可以工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.