Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

arrays - Extract part of a text file for usage in vb.net

Ok. I need to store some records in a file namely data.dat. Records in the file are sorted by date values. Each block of record starts with its date value along with a $ sign to indicate that a new block of record starts here and ends with a "#" sign to indicate end of the record block.

A sample of a record block would be:

$22/08/2013
(data)
(data)
(data)
#

The file data.dat contains several blocks like this, how can I extract each block in the file storing each in an array using vb.net?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of an array i would use a List(Of T). You could create a custom class:

Class Record
    Public Property DateValue As DateTime
    Public Property Data As New List(Of String)
End Class

Here's a possible loop to initialize the list from your file:

Dim allData As New List(Of Record)
Dim currentRecord As Record = Nothing
Dim currentData As List(Of String) = Nothing
For Each line In File.ReadLines("data.dat")
    If line.StartsWith("$") Then
        Dim dt As DateTime
        If Date.TryParse(line.Substring(1), dt) Then
            currentRecord = New Record()
            currentRecord.DateValue = dt
            currentData = New List(Of String)
            currentRecord.Data = currentData
        End If
    ElseIf currentRecord IsNot Nothing Then
        If line.EndsWith("#") Then
            allData.Add(currentRecord)
        Else
            currentData.Add(line)
        End If
    End If
Next

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...