使用StreamReader从文本文件加载某些值

时间:2013-03-27 13:18:36

标签: vb.net streamreader

我是Visual Basic的新手所以我需要一些帮助才能开始我正在开发的项目。我使用StreamReader打开包含学生姓名和成绩的文本文件,但我想从文本文件中选择某些值(例如,他们的最高分,平均分和总分数)。我最好创建一个数组来显示这些值或编写函数来检索我想要的数据吗?我有点茫然,不想浪费我的时间,所以任何建议都会非常受欢迎。

数据存储为txt文件,如下所示:学生姓名,年级1,年级2,年级3,年级4,整体商标。

感谢。

2 个答案:

答案 0 :(得分:1)

我将创建一个具有所需属性的类,然后创建一个(Object)列表。请参阅下面的示例。

Public Sub GetStudentData()
    Dim oStudents As New List(Of Student)
    Using r As IO.StreamReader = New IO.StreamReader("file.txt")
        ' Store contents in this String.
        Dim line As String

        ' Read first line.
        line = r.ReadLine
        oStudents.Add(New Student(line))
        Do While (line IsNot Nothing)
            ' Read in the next line.
            line = r.ReadLine
            oStudents.Add(New Student(line))
        Loop
    End Using
End Sub

Public Class Student
    Public Property StudentID As String
    Public Property FirstName As String
    Public Property LastName As String
    Public Property HighestGrade As String
    Public Property Averages As String
    Public Property OverAllMarks As String

    Public Sub New(line As String)
        _StudentID = line ' Get specific string from text line
        _FirstName = line ' Get specific string from text line
        _LastName = line ' Get specific string from text line
        _HighestGrade = line ' Get specific string from text line
        _Averages = line ' Get specific string from text line
        _OverAllMarks = line ' Get specific string from text line
    End Sub
End Class

答案 1 :(得分:0)

Private Sub btnAverage_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)处理btnAverage.Click

    Using myreader As New Microsoft.VisualBasic.FileIO.TextFieldParser("c:\Users\documents\studentresults.txt")
        myreader.TextFieldType = FileIO.FieldType.Delimited
        myreader.SetDelimiters(",")
        Dim currentrow As String()
        While Not myreader.EndOfData
            Try
                currentrow = myreader.ReadFields()
                Dim average As Double
                currentrow.Skip(1).Skip(2).Average(Function(s) Convert.ToDouble(s))
                MsgBox("Average is " & currentrow(0))
                Convert.ToString(average)
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                MsgBox("line" & ex.Message &
                       "is not valid and will be skipped")
            End Try
        End While
    End Using 

这是我到目前为止的代码,所以任何建议都会很棒。