How To: Read String Line by Line

Breaking a string containing multi-line text to a list of lines can be easily done using StringReader. Here is a method that does this and small test program:


class Program
{
    static void Main(string[] args)
    {
        IList<string> lines = BreakLines("This is a test for breaking multiline string \nto a list of lines.");

        foreach (var item in lines)
        {
            Console.WriteLine(item);
        }

        Console.ReadLine();
    }

    private static IList<string> BreakLines(string text)
    {
        IList<string> lines = new List<string>();

        using (StringReader reader = new StringReader(text))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }

        return lines;
    }
}

 

About khymenko

Developing for Windows and Windows Phone

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

I’m Tweeting

Follow

Get every new post delivered to your Inbox.