如何将 txt 文件中的字符串数据流式传输到数组中

How to Stream string data from a txt file into an array


我正在实验室做这个练习。说明如下

此方法应从名为“catalog.txt”的文本文件中读取产品目录,您应该 与您的项目一起创建。每个产品都应在单独的 line.Use 视频中创建文件并将其添加到您的项目的说明,并向 return 包含文件前 200 行的数组(使用 StreamReader class 和 while 循环读取 从文件中)。如果文件超过 200 行,请忽略它们。如果文件少于 200 行, 如果某些数组元素为空 (null) 也可以。

我不明白如何将数据流式传输到字符串数组中,如有任何说明,将不胜感激!

    static string[] ReadCatalogFromFile()
    {
        //create instance of the catalog.txt
        StreamReader readCatalog = new StreamReader("catalog.txt");

        //store the information in this array
        string[] storeCatalog = new string[200];
        int i = 0;

       //test and store the array information
        while (storeCatalog != null)
        {

            //store each string in the elements of the array?
            storeCatalog[i] = readCatalog.ReadLine();
            i = i + 1;
            if (storeCatalog != null)
            {
                //test to see if its properly stored

                Console.WriteLine(storeCatalog[i]);
            }
        }
        readCatalog.Close();
        Console.ReadLine();
        return storeCatalog;
    }

这里有一些提示:

int i = 0;

这需要在您的循环之外(现在每次都重置为 0)。

在您的 while() 中,您应该检查 readCatalog() and/or 最大读取行数的结果(即 array 的大小)

因此:如果您到达文件末尾 -> 停止 - 或者如果您的数组已满 -> 停止。

A​​ for-loop 当您事先知道确切的迭代次数时使用。所以你可以说它应该正好迭代 200 次,这样你就不会越过索引边界。目前您只需检查您的数组是否不为空,它永远不会为空。

using(var readCatalog = new StreamReader("catalog.txt"))
{
  string[] storeCatalog = new string[200];

  for(int i = 0; i<200; i++)
  { 
    string temp = readCatalog.ReadLine();
    if(temp != null)
      storeCatalog[i] = temp;
    else 
      break;
  }

  return storeCatalog;
}

一旦文件中不再有行,temp 将为空并且循环将由 break 停止。 我建议您在 using 语句中使用一次性资源(如任何流)。大括号中的操作完成后,资源将自动释放。

static string[] ReadCatalogFromFile()
{
    var lines = new string[200];
    using (var reader = new StreamReader("catalog.txt"))
        for (var i = 0; i < 200 && !reader.EndOfStream; i++)
            lines[i] = reader.ReadLine();
    return lines;
}