使用 StreamReader 读取由其他行定义的行

Using StreamReader to read lines as defined by other lines

我遇到了一个问题,需要我根据文本文件计算综合学生分数。它在第一行给出了分数的权重,在下一行给出了要评估的学生人数,然后下一行是学生的分数。此模式在文件中重复出现,没有大的分隔。

为清楚起见,文本文件和问题是 here:

我试过使用以下代码用 streamreader 创建一个新对象:

using (StreamReader sr = new StreamReader("DATA10.txt")) {
    blahblahblah;
}

DATA10.txt 与程序在同一文件夹中。

但我得到 "Cannot convert from 'string' to 'System.IO.Stream'",即使在 MSDN 和其他地方的示例中也可以很好地使用该确切代码。我做错了什么?

最终我要做的是从第二行中获取值并使用 streamreader 读取该行数。然后在下一组数据上重复整个过程。

我真的不认为这是那个问题的重复,这里的答案是用更容易理解的方式表达的。

您还必须在解决方案资源管理器中将 "DATA10.txt" 的 "Copy to output directory" 属性 设置为 "Copy Always"

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace _07___ReadTextFileWhile
    {
        class Program
        {
            static void Main(string[] args)
            {
                StreamReader myReader = new StreamReader("DATA10.txt");

                string line = "";

                while (line != null)
                {
                    line = myReader.ReadLine();
                    if (line != null)
                        Console.WriteLine(line);
                }

                myReader.Close();
                Console.ReadKey();

            }
        }
    }

StreamReader 假设接受一个Stream作为它的参数也可以接受一个Stream作为参数并且你还必须指定FileMode.

相反,尝试这样的事情:

public static void Main() 
{
    string path = @"c:\PathToFile\DATA10.txt";

    try 
    {        
        using (FileStream fs = new FileStream(path, FileMode.Open)) 
        {
            using (StreamReader sr = new StreamReader(fs)) 
            {
                 //blahblah    
            }
        }
    } 
    catch (Exception e) 
    {
        Console.WriteLine("The process failed: {0}", e.ToString());
    }
}

MSDN Reference