我不相信这一点:
当我将核心框架移动到 Windows 服务中时,Environment.NewLine 更改为“\n”
我已经检查了 IL get_NewLine()
,它被硬编码为:
ldstr "\r\n"
ret
所以基本上;问题不是你想的那样;改变Environment.NewLine
不会做任何事情(并且:不可能)。
那么:你是如何重定向的?我倾向于做类似的事情:
if (!Environment.UserInteractive)
{
var tw = new SlowWriter(Path.Combine(logPath,"{0}.log"));
Console.SetError(tw);
Console.SetOut(tw);
}
哪里是确保文件不会保持打开状态SlowWriter
的自定义类型(子类);TextWriter
较慢,但相当健壮:
class SlowWriter : TextWriter
{ // this opens and closs each time; slower, but doesn't lock the file
private readonly string path;
public SlowWriter(string path)
{
this.path = path;
}
public override System.Text.Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
private TextWriter Append()
{
var finalPath = string.Format(path, DateTime.UtcNow.ToString("yyyyMMdd"));
return File.AppendText(finalPath);
}
public override void Write(string value)
{
lock (this)
{
using (var file = Append())
{
file.Write(value);
}
}
}
public override void Write(char[] buffer, int index, int count)
{
lock(this)
{
using (var file = Append())
{
file.Write(buffer, index, count);
}
}
}
public override void Write(char[] buffer)
{
lock (this)
{
using (var file = Append())
{
file.Write(buffer);
}
}
}
}