如何使用 streamreader 从外部文件填充列表

How to fill a list from an external file using streamreader

如何在 (List words) 中制作一个单词列表并用方法 void ReadWords(string, List. 此方法必须获取文件的名称:文本和列表必须填充此文件中的单词。

那我该怎么做呢?

我从这个开始:

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();

因此,您需要做的是从文件中提取行,并了解如何拆分每个单词。然后实际将其添加到您的列表中,我在下面添加了一些相关代码。

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();