Son Goku
Son Goku

Reputation: 19

How to fill a list from an external file using streamreader

how do i make a list of words in (List words) and fill it with a method void ReadWords(string, List. this method has to get the name of the file: text and the list must be filled with the words from this file.

so how do i do this?

i started with this:

List<string> woorden = new List<string>();

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("txt.txt");

int counter = 0;

while (!file.EndOfStream)
{
     string woord = file.ReadLine();

     for (int i = 0; i < woord.Length; i++)
          counter++;

}
Console.WriteLine(counter);
file.Close();
Console.ReadKey();

Upvotes: 1

Views: 6549

Answers (1)

Scriven
Scriven

Reputation: 438

So what you need to do is take the line from the file and some how split each word up. Then actually add it to your list, I've added some relevant code below.

List<string> woorden = new List<string>();

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("txt.txt");
while (!file.EndOfStream)
{
   string woord = file.ReadLine();
   string[] words = woord.Split(' ') //This will take the line grabbed from the file and split the string at each space. Then it will add it to the array
   for (int i = 0; i < words.Count; i++) //loops through each element of the array
   {
      woorden.Add(words[i]); //Add each word on the array on to woorden list
   }
}
Console.WriteLine();
file.Close();
Console.ReadKey();

Upvotes: 2

Related Questions