.NET Environment.NewLine - 如何以编程方式设置

时间:2012-07-27 09:11:01

标签: c# .net newline environment

我想更改当前环境的默认Environment.NewLine字符。

我有一个将消息写入控制台的独立应用程序。当核心框架在控制台环境中工作时,新行是\ r \ n。当我将核心框架移动到Windows服务时,Environment.NewLine变为“\ n”。

我希望能够将控制台更改为始终使用“\ r \ n”,因为当我将控制台的输出重定向到文件时,从示例记事本中读取时输出没有“windows new lines”。 / p>

我希望Console.WriteLine在我想要的时候使用\ r \ n。

修改

我正在重定向Console.out:

        ConsoleOut = File.AppendText(fileName);
        ConsoleOut.AutoFlush = true;


        Console.SetOut(ConsoleOut);
        Console.SetError(ConsoleOut);

每个Console.WriteLine或Console.Write都会发送到一个文件,但正如我所说,我在Windows服务和独立Windows环境中遇到了不同的行为。

3 个答案:

答案 0 :(得分:4)

我不相信:

  

当我将核心框架移动到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);
            }
        }
    }
}

答案 1 :(得分:2)

您无法修改System.Environment.NewLine

MSDN Reference

这是一个只读属性

public static string NewLine { get; }

Here你可以看到NewLine总是返回“\ r \ n”。

  

接下来我们查看get_NewLine并使用此IL实现。您   可以看到它只返回“\ r \ n”字符串文字。

所以我认为你可以在你的应用程序中使用一个常量,如

public const NEWLINE = "\r\n"; 

只需使用它而不是Environment.NewLine。

Console.WriteLine不在内部使用Environment.NewLine,而是使用回车符后跟换行符。参考Here

  

默认行终止符是一个字符串,其值为一个回车符   返回后跟换行符(C#中的“\ r \ n”,或Visual中的vbCrLf)   基本)。您可以通过设置更改行终止符   Out属性的TextWriter.NewLine属性为另一个字符串。该   示例提供了说明。

还有一个关于如何修改此属性的示例:

 // Redefine the newline characters to double space.
 Console.Out.NewLine = "\r\n\r\n";

答案 2 :(得分:1)

然后我认为你不应该使用Environment.NewLine。你看到的是它首先拥有它的确切原因。我认为通过定义您使用的appSettings并将其设置为控制台应用程序和Windows服务应用程序的不同值,您会感觉更好。

更新的 另见Marc Gravell的回答。即使它是硬编码的,我也不会尝试用上面的动机来改变它。