Substring generates error


B

Bruce D

I've found a problem in my program. I'm reading a file (fixed length) and
I'm using a structure to return the values...all ok. But the problem arises
when the length of the line I'm reading isn't as long as it's supposed to
be. Then my substring() function throws an error. Below is my code.

Public Structure strucRecord
Public strLine As String
Public ReadOnly Property AssignCity() As String
Get
AssignCity = strLine.Substring(335, 15).Trim
End Get
End Property
End Structure

Dim rec As New strucRecord
Dim sr As StreamReader = New StreamReader(Me.txtFile.Text)
rec.strLine = sr.ReadLine

* While looping through this file, there are a few lines in file that have a
length of 300? I haven't figured that one out. So, when I go to access
"rec.AssginCity" it throws an error. Anyhow, I'm wondering if I need to put
an "IF" statement in the "GET"...checking on length...or is there a better
way??

TIA
-bruce
 
Ad

Advertisements

R

rawCoder

Its always better to check for the error before hand.

HTH
rawCoder
 
C

Cor Ligthert

BruceD,

Use an "If" to check if the instruction can be done.
Its always better to check for the error before hand.

:)

Cor
 
Ad

Advertisements

C

Chris Dunaway

Another alternative is to pad the string when you read it in so that it
always has the correct length. Of course your property might return an
empty string in that case.

rec.strLine = sr.ReadLine.PadRight(maxlength," "c)
 

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

Similar Threads


Top