2011-08-14 80 views
2

的数组,我有以下结构:从顺序文件读入结构

public struct StudentDetails 
    { 
     public string unitCode; //eg CSC10208 
     public string unitNumber; //unique identifier 
     public string firstName; //first name 
     public string lastName;// last or family name 
     public int studentMark; //student mark 
    } 

使用结构我写数据到一个顺序文件。该文件中的数据如下:

ABC123 
1 
John 
Doe 
95 
DCE433 
3 
Sherlock 
Holmes 
100 
ASD768 
5 
Chuck 
Norris 
101 

什么是从文件中读取数据,并将其加载到结构的数组的最佳方式?

+1

是字符串是固定大小还是变量? – BrokenGlass

+0

@BrokenGlass:变量,因为名字和姓氏的长度会有所不同 – n1te

回答

1

假设你文件是每行一个值:

List<StudentDetails> studentList = new List<StudentDetails>(); 

using (StreamReader sr = new StreamReader(@"filename")) 
{ 

    while (!sr.EndOfStream) 
    { 
     StudentDetails student; 

     student.unitCode = sr.ReadLine(); 
     student.unitNumber = sr.ReadLine(); 
     student.firstName = sr.ReadLine(); 
     student.lastName = sr.ReadLine(); 
     student.studentMark = Convert.ToInt32(sr.ReadLine()); 

     studentList.Add(student); 
    } 

    StudentDetail[] studentArray = studentList.ToArray(); 

} 

注意,这并不是很稳定 - 如果没有5号线为每一位学生,你会碰到的问题,或者如果最后一个学生有不超过5行。

编辑

以教训从以前的问题Array of structs in C#了解到关于需要在struct覆盖ToString(),下面可能帮助打印值来解决此问题:

在StudentDetails结构(摘自尼克布拉德利的回答):

public override string ToString() 
{ 
    return string.Format("{0}, {1}, {2}, {3}, {4}", unitCode, 
      unitNumber, firstName, lastName, studentMark); 
} 

然后,你可以简单地循环阵列:

for (int i = 0; i < studentArray.Length; i++) 
{ 
    Console.WriteLine("Student #{0}:", i); 
    Console.WriteLine(studentArray[i]); 
    Console.WriteLine(); 
} 
+0

该代码有效,但studentArray不会打印除CA4.Program.StudentDetails之外的任何内容,任何想法? – n1te

+0

根据你以前的问题,它看起来像你需要重写你的结构中的'ToString()'方法。你可以发布没有正确执行的代码吗?看到我编辑的答案。 – Tim

+0

我已通过电子邮件发送给您。 – n1te

1

最初我会用某种Serialization来写入文件,因为它也会照顾阅读部分。
但考虑到你所创建的文件的方式,I'de使用StreamReader和它的ReadLine()方法 - 因为你知道是什么属性的顺序您写信给服务器的简单而:

string line = ""; 
while ((line = reader.ReadLine()) != null) 
{ 
    YourStruct t = new YourStruct(); 
    t.unitCode = line; 
    t.unitNumber = reader.ReadLine(); 
    ... 
    resultArray.Add(t); 
} 
reader.Close(); reader.Dispose(); 
+0

while循环中的'(line = reader.ReadLine())!= null'条件会抛出该行, t在while循环中做任何事情。 – Tim

+0

@Tim - 修好了,谢谢! – sternr