Reading Fixed Length ASCII/Text File

K

Ken Hall

I have the following code to read the following file (very simple).
I'm trying to extract only the date, but with this code I'm extracting
the entire record. What am I doing wrong? What am I missing?

Ken

c:\temp\namedate.txt = Ken Hall08/27/56 (One record)

Module Module1

Public Structure Record1
<VBFixedString(8)> Public name As String
<VBFixedString(8)> Public date1 As String
End Structure


Sub Main()
Try
Dim line As String
Dim Record2 As New Record1

' Create an instance of StreamReader to read from a file.
Dim sr As System.IO.StreamReader = New
System.IO.StreamReader("c:\temp\namedate.txt")
' Read and display the lines from the file until the end
' of the file is reached.
Do
line = sr.ReadLine()
Record2.date1 = line
Console.WriteLine(Record2.date1)
Loop Until line Is Nothing
sr.Close()
Catch E As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(E.Message)
End Try


End Sub

End Module
 
T

Tom Leylan

Ken Hall said:
I have the following code to read the following file (very simple).
I'm trying to extract only the date, but with this code I'm extracting
the entire record. What am I doing wrong? What am I missing?
Record2.date1 = line

I think the "error" is this line where you intend to assign the value of the
line to Record2 not the date1 member of that structure. However... (there
is always a however) you can't assign a string to a structure of Record1
type. So that's not going to work either.

How about something like this (I named it RecStruct rather than Record1:

Public Structure RecStruct

Public data As String

Public ReadOnly Property name() As String
Get
name = data.Substring(0, 8)
End Get
End Property

Public ReadOnly Property date1() As String
Get
date1 = data.Substring(8, 8)
End Get
End Property

End Structure


Now you can read directly into it:

Rec.data = sr.ReadLine()

and output the properties:

Debug.WriteLine(Rec.name)
Debug.WriteLine(Rec.date1)

you'll have to adjust your do... loop until a bit also as it will attempt to
output the name and date1 when rec.data is nothing unless you skip over
those lines

Tom
 
H

Herfried K. Wagner [MVP]

* "Tom Leylan said:
I think the "error" is this line where you intend to assign the value of the
line to Record2 not the date1 member of that structure. However... (there
is always a however) you can't assign a string to a structure of Record1
type. So that's not going to work either.

Really nice solution.

:)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top