我在dll文件中有一个函数,它写了一些标准输出和标准错误。如何阅读此函数写入字符串的内容?
答案 0 :(得分:1)
您可以将应用程序的标准和错误输出重定向到stringwriters,然后使用它们。像这样:
static void Main()
{
using (StringWriter writer = new StringWriter(), errorWriter = new StringWriter())
{
var stdOut = Console.Out;
var stdErr = Console.Error;
Console.SetOut(writer);
Console.SetError(errorWriter);
try
{
MyDllWritesThings();
}
finally
{
Console.SetOut(stdOut);
Console.SetError(stdErr);
}
Print("StdOut", writer);
Print("StdErr", errorWriter);
}
Console.ReadKey();
}
private static void Print(string what, StringWriter writer)
{
writer.Flush();
using (var reader = new StringReader(writer.ToString()))
{
var wowInteresting = reader.ReadToEnd();
Console.WriteLine($"{what}: '{wowInteresting}'");
}
}
private static void MyDllWritesThings()
{
Console.WriteLine("Secret output");
Console.Error.WriteLine("Secret error output");
}