Easiest way to Add lines wrong a .txt file to a list

86 views Asked by At

At the moment I am opening the .txt file twice, once to get the number of all the lines, second to add a line to a list as much as how much lines there are in the .txt file. Is there an easier/better way to do this?

This is my code:

List<StreamReader> lijst = new List<StreamReader>();
StreamReader something1 = new StreamReader("C:\\something123.txt");
StreamReader something2 = new StreamReader("C:\\something123.txt");

lijst.Add(something1);
lijst.Add(something2);
{
    int l = 0;
    while (lijst[1].ReadLine() != null) 
    { 
        l++;
        downloadLinks.Add(lijst[1].ReadLine());
    }

    for (int i = 0; i < l; i++)
    {
        String line = lijst[0].ReadLine();
        aList.Add(line);
    }
 }
2

There are 2 answers

13
Yuval Itzchakov On BEST ANSWER

I want to put all the lines of the file in a list

Then you are working currently working too hard. You can use File.ReadLines, which yields an IEnumerable<string> and pass that into a List<string>:

var allTextLines = new List<string>(File.ReadLines(path));
0
n00b On

You can use this function to read all lines in one go. This way you don't need to iterate through a loop and the results are going to be in an Array that can be added in one call to any list you want.

var lines = File.ReadAllLines(filepath);
downloadLinks.AddRange(line);

https://msdn.microsoft.com/en-us/library/system.io.file.readalllines(v=vs.110).aspx