I had a requirement to create a TextWriter to populate some data. I used the StringWriter as a TextWriter and the business logic works fine. 
I have a technical requirement that cannot be changed because it may break all the clients. I need to  an array of strings string[] from the TextWriter separated by line.
I tried with this but didn't work:
using System;
using System.IO;
using System.Text;
namespace TextWriterToArrayOfStringsDemo
{
    internal static class Program
    {
        private static void Main()
        {
            var stringBuilder = new StringBuilder();
            using (TextWriter writer = new StringWriter(stringBuilder))
            {
                writer.Write("A");
                writer.WriteLine();
                writer.Write("B");
            }
            string fullString = stringBuilder.ToString();
            string replaced = fullString.Replace('\n', '\r');
            string[] arrayOfString = replaced.Split('\r');
            // Returns false but should return true
            Console.WriteLine(arrayOfString.Length == 2);
        }
    }
}
Any idea or suggestion?
Try using Environment.NewLine to split rather than '\n':
        var stringBuilder = new StringBuilder();
        using (TextWriter writer = new StringWriter(stringBuilder))
        {
            writer.Write("A");
            writer.WriteLine();
            writer.Write("B");
        }
        string fullString = stringBuilder.ToString();
        string[] newline = new string[] { Environment.NewLine };
        string[] arrayOfString = fullString.Split(newline, StringSplitOptions.RemoveEmptyEntries);
        // Returns false but should return true
        Console.WriteLine(arrayOfString.Length == 2);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With