将C#多行字符串文字写入文件并以CRLF结尾

时间:2018-09-21 20:29:48

标签: c# .net-core

我试图将多行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

2 个答案:

答案 0 :(得分:0)

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

以上问题讨论了使用另一种机制来理解行尾的编写方法:Writing Unix style text file in C#

但是正如我所here所指出的那样,它不适用于C#多行字符串,因此在我的情况下,我不得不使用Replace("\r\n", "\n")

答案 1 :(得分:-4)

您应该改用Environment.NewLine。

相关问题