【问题标题】:Writing C# multi-line string literal to a file and CRLF line ending将 C# 多行字符串文字写入文件和 CRLF 行结尾
【发布时间】:2018-09-21 20:29:48
【问题描述】:

我试图将多行 C# 字符串文字写入文件,并注意到字符串文字的行尾始终为 CRLF。

提供更多背景信息:我正在使用 .NET Core 2.1,并且正在 Linux 中构建和运行此示例应用程序。

注意我没有使用Git,所以这与Git 行尾处理无关。

这是预期的吗?我希望行尾实际上是 LF 而不是 CRLF。

复制代码:

   class Program
    {
        const string script =
        @"#!/bin/bash
echo Hello
echo Hi
echo Hey
";

        static void Main(string[] args)
        {
            string text;
            if (args.Length > 0)
            {
                // This gets written as CRLF
                text = script;
            }
            else
            {
                // This gets written as LF(probably because StringBuilder figures
                // in which OS its running and does the right thing)
                var sb = new StringBuilder();
                sb.AppendLine("#!/bin/bash");
                sb.AppendLine("echo Hello");
                sb.AppendLine("echo Hi");
                sb.AppendLine("echo Hey");
                text = sb.ToString();
            }

            var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid().ToString("N")}.sh");
            File.WriteAllText(path, text);
            Console.WriteLine($"Text written to {path}");
        }
    }

更新

仅供有兴趣的人参考...我在这里发布了一个关于此的问题:https://github.com/dotnet/csharplang/issues/1877

【问题讨论】:

  • 我猜\r\n 在编译器中是硬编码的。但需要确认。
  • Also this is not a duplicate 重复状态Since no exception is made for line endings, you get whatever line endings were used in the source file. As you found out. 这感觉与您的问题非常相关。您是如何得出不相关的结论的?

标签: c# .net-core


【解决方案1】:

我在这里https://github.com/dotnet/csharplang/issues/1877 发布了一个与此相关的问题,看来这是预期的行为。

上面的问题谈到了使用另一种机制来理解写行结尾,如下所示:Writing Unix style text file in C#

但是,正如我所说的 here,它不适用于 C# 多行字符串,所以我不得不求助于使用 Replace("\r\n", "\n")

【讨论】:

  • 这与我发布的副本完全一致。如果源代码有 crlf,那么您将看到预期的行为。
  • @mjwills:这与 Git 无关,需要明确的是,我什至没有使用版本控制系统。这就是 C# 编译器的工作原理。
【解决方案2】:

您应该改用 Environment.NewLine。

【讨论】:

    猜你喜欢
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多