read line from textfile

sony

Member
Joined
Oct 12, 2005
Messages
9
hi i am using winforms in vb.net .. i have this for loop which is below basically i am reading the firstline from a textfile there are empty spaces between the text it is returning therefor everywhere, where there is a space i am adding a number.

this is working fine but for some reason after reading the last string which the textfile the for loop keeps on going and adding another extra column for me . can someone tell me how i can make the for loop to stop as soon as it at the end of the first line where there is the last string..

thanks in advance
Code:
  Dim oSR As New StreamReader(strFilePath)

        GO TO THE TOP OF THE FILE AND GET THE BEGIN
        oSR.BaseStream.Seek(0, SeekOrigin.Begin)

        ADD THE HEADER COLUMNS TO THE DATSET 
        Dim strFieldss As String
        For Each strFields In oSR.ReadLine().Split(strdelimeter)
            If strFields = "" Then
                strFields = i
            End If
            i = i + 1
            oDT.Columns.Add(strFields)

        Next
 
What you are trying to accomplish could probably be done in a better way.

Did you copy the code, because the declaration of your variable is spelled strFieldss, whereas your using strFields.

Code:
  Dim strFieldss As String

Where is (the variable) i coming from?

Also, you should compare strFields to string.Empty instead of ""

Also, this is called boxing...

Code:
 strFields = i

and is considered a performance no-no.


Also, the Split function takes a char array, so naming the parameter strDelimiter is misleading.

Code:
 For Each strFields In oSR.ReadLine().Split(strdelimeter)

Also, Im sure you know, but your code only reads one line from the file...
if you want to read the whole file, just surround the for next loop with

while (oSR.Read())

end while


Now, to the actual problem...

The extra column its adding, Im assuming is a number? The only way I can see that an extra column would be added if there were spaces after the last word on the first line. The [easiest], and Im assuming you want the easiest solution is this

Code:
   For Each strFields In oSR.ReadLine().Trim().Split(strDelimiter)
 
Back
Top