Monday, November 21, 2016

Read a Text File One Line at a Time to the List (C#)

This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and added to the list.

public static List<string> ReadFromFile(string path)
        {
            List<string> lineList = new List<string>();
            using (StreamReader reader = new StreamReader(path))
            {
                string line;

                while ((line = reader.ReadLine()) != null)
                {
                    lineList.Add(line);
                }

            }
            return lineList;
        }

No comments:

Post a Comment