简体   繁体   中英

Writing C# multi-line string literal to a file and CRLF line ending

I was trying to write out a multi-line C# string literal to a file and noticed that the line endings of the string literal is always CRLF.

To give more context: I am using .NET Core 2.1 and I am building and running this sample app in Linux .

Note I am not using Git so this is not related to Git line ending handling.

Is this expected? I was hoping that the line endings would actually be LF and not CRLF.

Repro code:

   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}");
        }
    }

Update

Just FYI for anyone who is interested...I posted a question about this over here: https://github.com/do.net/csharplang/issues/1877

I posted an issue related to this over here https://github.com/dotnet/csharplang/issues/1877 and it appears this is an expected behavior.

The above issue talks about using another mechanism which understands writing line endings as here: Writing Unix style text file in C#

However as noted here by me, it does not work for C# multi-line strings, so I had to resort to using Replace("\\r\\n", "\\n") instead in my case.

The answer is the same as https://stackoverflow.com/a/48196962/771768

If your C# source file has CRLF ending, the multiline string will have CRLF.

If the source file has LF endings, the string will have LF.

If your source file has mixed LF and CRLF, then the string will have mixed LF and CRLF endings. But other devs will rightfully complain that this will be confusing.

您应该改用Environment.NewLine。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM