Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert StringWriter to string[]

Tags:

c#

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?

like image 300
rcarrillopadron Avatar asked Apr 24 '12 17:04

rcarrillopadron


1 Answers

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);
like image 181
Khan Avatar answered Oct 08 '22 11:10

Khan