0

我有一个学生的文本文件,我必须阅读它并将其保存在数组列表中。文件的形式是第一名,第二名,标记,每个名字都写在一个新行中,请帮助我如何做文件格式:

First Name
Last Name
Marks
First Name
Last Name
Marks
First Name
Last Name
Marks

这是我到目前为止所尝试的:

List<string> fileContent = new List<string>(); 
TextReader tr = new StreamReader("A.txt"); 
string currentLine = string.Empty; 
while ((currentLine = tr.ReadLine()) != null) 
{ 
    fileContent.Add(currentLine); 
} 
4

2 回答 2

1

下面是一个读取您指定格式的文件并将结果推送到 People 列表(或 ArrayList,如果您愿意)的示例。基于此,如果这是您的偏好,您应该能够创建一个字符串列表,尽管我怀疑您想要一个人员列表?

class Program
{
    static void Main(string[] args)
    {
        string fn = @"c:\myfile.txt";
        IList list = new ArrayList();
        FileReader(fn, ref list);
        for (int i = 0; i < list.Count; i++)
        {
            Console.WriteLine(list[i].ToString());
        }
        Console.ReadKey();
    }
    public static void FileReader(string filename, ref IList result)
    {
        using (StreamReader sr = new StreamReader(filename))
        {
            string firstName;
            string lastName;
            string marks;
            IgnoreHeaderRows(sr);
            while (!sr.EndOfStream)
            {
                firstName = sr.EndOfStream ? string.Empty : sr.ReadLine();
                lastName = sr.EndOfStream ? string.Empty : sr.ReadLine();
                marks = sr.EndOfStream ? string.Empty : sr.ReadLine();
                result.Add(new Person(firstName, lastName, marks));
            }
        }
    }
    const int HeaderRows = 2;
    public void IgnoreHeaderRows(StreamReader sr)
    {
        for(int i = 0; i<HeaderRows; i++)
        {
            if(!sr.EndOfStream) sr.ReadLine();
        }
    }
}

public class Person
{
    string firstName;
    string lastName;
    int marks;
    public Person(string firstName, string lastName, string marks)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        if (!int.TryParse(marks, out this.marks))
        {
            throw new InvalidCastException(string.Format("Value '{0}' provided for marks is not convertible to type int.", marks));
        }
    }
    public override string ToString()
    {
        return string.Format("{0} {1}: {2}", this.firstName, this.lastName, this.marks);
    }
    public override int GetHashCode()
    {
        return this.ToString().GetHashCode();
    }
}
于 2013-09-02T21:32:27.617 回答
0

JohnLBevan - 要在 FileReader 中调用 IgnoreHeaderRows,我们需要将 IgnoreHeaderRows 更改为静态,因为不能在静态方法中访问非静态成员。如我错了请纠正我。

于 2014-01-10T19:36:22.123 回答