如何通过关键字搜索.dat文件中的特定记录

时间:2014-05-01 17:20:11

标签: vb.net

所以我有一个列表框,显示.dat文件的内容。

文件中的每条记录都有名称,时间,地点和描述。

在我的表单上有一个搜索按钮,点击后,我希望用户能够输入一个名称来检查该特定记录是否存在。如果是这样,我希望msgbox按照我之前提到的顺序显示整个记录。另一方面,如果不是我想要一个msgbox显示无法找到记录。

1 个答案:

答案 0 :(得分:0)

假设一个制表符分隔文件,在记录之间回车,第一个字段是您正在搜索的字段(编辑给我更完整,更符合问题):

Public Class Form1
    Public Function FindRecord(name As String, path As String) As Record
        Using reader As New IO.StreamReader(path)
            Do While Not reader.EndOfStream
                Dim line As String = reader.ReadLine
                Dim record As Record = record.FromLine(line)
                If record.Name = name Then
                    Return record
                End If
            Loop
        End Using
        Return Nothing
    End Function

    Public Class Record
        Public Property Name As String
        Public Property Time As Date
        Public Property Location As String
        Public Property Description As String

        Public Shared Function FromLine(line As String) As Record
            Dim record As Record = Nothing

            Dim fields() As String = line.Split(ControlChars.Tab)
            If fields.Length = 4 Then
                record = New Record
                record.Name = fields(0)
                record.Time = Date.Parse(fields(1))
                record.Location = fields(2)
                record.Description = (3)
            Else
                Throw New FormatException("Line is not in the correct format.")
            End If
            Return record
        End Function
    End Class
End Class