By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,579 Members | 1,618 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,579 IT Pros & Developers. It's quick & easy.

Substring generates error

P: n/a
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

Nov 21 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Its always better to check for the error before hand.

HTH
rawCoder

"Bruce D" <br*************@hotmail.com> wrote in message
news:11*************@corp.supernews.com...
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

Nov 21 '05 #2

P: n/a
BruceD,

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

:-)

Cor
Nov 21 '05 #3

P: n/a
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)

Nov 21 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.