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

时间:2015-12-29 23:15:24

标签: c# arrays streamreader

我正在从实验室进行这项练习。说明如下

此方法应从您应该使用的名为“catalog.txt”的文本文件中读取产品目录 与您的项目一起创建。每个产品应该在一个单独的行上。使用视频中的说明创建文件并将其添加到项目中,并返回 来自文件的前200行的数组(使用StreamReader类和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;
    }

3 个答案:

答案 0 :(得分:2)

以下是一些提示:

chai-as-promised.js

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

int i = 0; 中,您应检查while()的结果和/或要读取的最大行数(即readCatalog()的大小)

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

答案 1 :(得分:0)

当您事先知道确切的迭代次数时,会使用for循环。所以你可以说它应该完全迭代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语句中使用您的可支配资源(如任何流)。在大括号中执行操作后,资源将自动处理。

答案 2 :(得分:0)

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;
}