【发布时间】:2015-12-31 03:41:47
【问题描述】:
我正在实验室做这个练习。说明如下
此方法应从名为“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;
}
【问题讨论】:
-
对于初学者,您应该使用 for 循环,但除此之外,实际上并没有更多功能。你有什么例外吗?
-
我得到的异常是:IndexOutOfRangeException。附加信息表明:索引超出了数组的范围
-
Matthew Whited 解决方案应该可以工作,但这并不好玩。如果你想让你的工作正常,请注意以下几点。 storeCatalog 永远不会为空,它是您创建的字符串数组对象。如果没有更多数据,ReadLine 将返回 null,请改用它。为了确保您的 StreamReader 被正确处理,即使您的代码崩溃了,您应该应用 try-finally 块,在创建 StreamReader 后立即开始,并且 Close() 应该在 finally 部分中。这相当于 Matthew 的 using 语句。
-
谢谢马丁!我意识到在数组、StreamReader 类甚至 null 方面我有很多工作要做,但我要感谢你帮助我澄清代码本身。我也会看看 try-finally 块。再次感谢
标签: c# arrays streamreader