What is a quick way to force CRLF in C# / .NET?

前端 未结 6 1536
独厮守ぢ
独厮守ぢ 2020-12-08 13:38

How would you normalize all new-line sequences in a string to one type?

I\'m looking to make them all CRLF for the purpose of email (MIME documents). Ideally this w

6条回答
  •  情书的邮戳
    2020-12-08 13:49

    It depends on exactly what the requirements are. In particular, how do you want to handle "\r" on its own? Should that count as a line break or not? As an example, how should "a\n\rb" be treated? Is that one very odd line break, one "\n" break and then a rogue "\r", or two separate linebreaks? If "\r" and "\n" can both be linebreaks on their own, why should "\r\n" not be treated as two linebreaks?

    Here's some code which I suspect is reasonably efficient.

    using System;
    using System.Text;
    
    class LineBreaks
    {    
        static void Main()
        {
            Test("a\nb");
            Test("a\nb\r\nc");
            Test("a\r\nb\r\nc");
            Test("a\rb\nc");
            Test("a\r");
            Test("a\n");
            Test("a\r\n");
        }
    
        static void Test(string input)
        {
            string normalized = NormalizeLineBreaks(input);
            string debug = normalized.Replace("\r", "\\r")
                                     .Replace("\n", "\\n");
            Console.WriteLine(debug);
        }
    
        static string NormalizeLineBreaks(string input)
        {
            // Allow 10% as a rough guess of how much the string may grow.
            // If we're wrong we'll either waste space or have extra copies -
            // it will still work
            StringBuilder builder = new StringBuilder((int) (input.Length * 1.1));
    
            bool lastWasCR = false;
    
            foreach (char c in input)
            {
                if (lastWasCR)
                {
                    lastWasCR = false;
                    if (c == '\n')
                    {
                        continue; // Already written \r\n
                    }
                }
                switch (c)
                {
                    case '\r':
                        builder.Append("\r\n");
                        lastWasCR = true;
                        break;
                    case '\n':
                        builder.Append("\r\n");
                        break;
                    default:
                        builder.Append(c);
                        break;
                }
            }
            return builder.ToString();
        }
    }
    

提交回复
热议问题