Why is streamreader not reading entire file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • edge691
    New Member
    • Jul 2010
    • 1

    Why is streamreader not reading entire file

    Hello All,

    I'm just getting into programming, bit of a newbie.

    I'm having an issue with the streamreader. I had it working but I've changed something and it has stopped.

    I have it in a Do While loop reading line by line, but it doesn't finish reading. It reads about 27 lines out of 4000, then stops.

    I changed the contents of the file it was reading, but it's still just save as a txt notepad file.

    I also changed how I tell it which file to open (UserSelection. T2) however it does open the file just doesn't finish reading it.

    Doesn't kick back any errors, it just doesn't read the entire file.

    Code:
    Dim FSO As Object
    Dim File As Object
    FSO = CreateObject("Scripting.FileSystemObject")
    File = FSO.OpenTextFile(UserSelection.T2, 1)
    File.ReadAll()
    Dim FileLength As Integer
    FileLength = File.line - 1
    Dim FileLengthCounter As Integer = 0
    Dim sLine As String = ""
    Dim objReader As New StreamReader(UserSelection.T2)
    
    Do While FileLengthCounter < FileLength
    sLine = objReader.ReadLine()
    
    If Not sLine Is Nothing Then
    Dim StringSearch As Integer = 0
    StringSearch = InStr(sLine.ToString, sTextDate)
    if StringSearch > 0 Then
          		
    'do stuff
    
    End If
    
    End If
    End If
    FileLengthCounter = FileLengthCounter + 1
    Loop
    objReader.Close()
  • Aimee Bailey
    Recognized Expert New Member
    • Apr 2010
    • 197

    #2
    It's fantastic that your getting into programming, to point you in the right direction, here's an example of what i would do...

    Code:
    Imports System.IO
    
    Public Class Form1
    
        Sub SearchFile(ByVal file As String,search As String)
    
            Using fs As New FileStream(file, FileMode.Open, _
                                       FileAccess.Read)
                Using sr As New StreamReader(fs)
    
                    Dim CurrentLine = sr.ReadLine()
                    If Not IsNothing(CurrentLine) And _
                        CurrentLine.Contains(search) Then
    
                        'do stuff
    
                    End If
    
                End Using
            End Using
    
        End Sub
    
    End Class
    Thanks to .Net's, there are many shorthand ways of doing things that save time. The example i've provided uses the FileStream and StreamReader directly, taking advantage of the Using keywords, we make sure that the file is closed and disposed once we have finished with it, and also using the String classes Contains function to make work much easier.

    Ofcourse this is a slightly narrowed way of doing things, but hopefully from the example you will be able to expand on it.

    Best Regards!

    Aimee

    Comment

    Working...