Console进行重定向到文件
2022-02-17 本文已影响0人
价值投机168
var stream = new FileStream("E:\log.txt", FileMode.Create);
Console.SetOut(new StreamWriter(stream));
做事
退出重定向:
Console.Out.Close();
Console.SetOut(new StreamWriter(Console.OpenStandardOutput(), Encoding.Default));//设置为默认的定向
完整代码:
private static FileStream stream = null;
public static void LogToFile(string path)
{
if (string.IsNullOrWhiteSpace(path)) { return; }
try
{
if (stream != null) { Console.Out.Close(); }
stream = new FileStream(path, FileMode.Create);
Console.SetOut(new StreamWriter(stream));
}
catch (Exception)
{
}
}
public static void LogToFileClose()
{
if (stream != null)
{
stream = null;
Console.Out.Close();
}
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}