Read a text file from bottom to top

Hello Guys,

I am using Visual Basic .net 2008 and need a little help.

I have several text files which contain some data. The data in text files is stored in a format like -


Now each file is over 2 MB in size. I need to read file from last line and check if I need to replace a record or not. If yes, then I can read the entire file and do the needful. If not then goto another file.

Now I do not want to read file from start to end. This will waste time specially if I figure that I do not need to modify the file. So how can I read from bottom to top so that as soon I come across the record I want to check I can determine if I need to modify the file or not. The possibility of finding required record lower down is very high.

I want this operation to run as fast as possible.

If you guys can give me a small code thru which I can read file from last record onwards to top and as fast as possible it will be great.

Thank you,

Who is Participating?
Dennis AriesConnect With a Mentor CEO @ Arkro ITCommented:
You would need FileStream.Seek to do that.
Microsoft MSDN has an example that reads a file backwards byte for byte, but you can easily convert that to longer sections.
Dim bytes() As Byte = New Byte(lengthOfRecord - 1) {}
fs.Seek(0, , SeekOrigin.End) ' jump to end of file '
fs.Seek(-lengthOfRecord, SeekOrigin.Current) ' go back a single record '
fs.Read(bytes, 0, lengthOfRecord) ' read your record into the byte-array '

Open in new window

The only thing that I think of is either read the entire file and get the last line ...

Or using some kind of seek-mechanism
John ClaesConnect With a Mentor Senior .Net Consultant & Technical AnalistCommented:

I can see 2 possiblilities. The first is my solution to this.
1) to read the Lines with the posiblity to use Linq to retrieve 1 line Fast : System.IO.File.ReadLines

2) to use the Filestream offset and Count to do you're own searching

This is an Example of ReadLines upon the IO.File object

The following example uses the ReadLines method in a LINQ query that enumerates all directories for files that have a .txt extension, reads each line of the file, and displays the line if it contains the string "Microsoft".

poor beggar
Imports System.IO
Imports System.Xml.Linq
Module Module1

    Sub Main()

            Dim files = From chkFile In Directory.EnumerateFiles("c:\", "*.txt", _
                        From line In File.ReadLines(chkFile)
                        Where line.Contains("Microsoft")
                        Select New With {.curFile = chkFile, .curLine = line}

            For Each f In files
                Console.WriteLine("{0}\t{1}", f.curFile, f.curLine)
			Console.WriteLine("{0} files found.", _
        Catch UAEx As UnauthorizedAccessException
        Catch PathEx As PathTooLongException
        End Try
    End Sub
End Module

Open in new window

This code reads your file from the buttom to the top. Where i commented is the place where you need to do your testing. this code is 7x faster than using the readline method.

Public Sub ReadTextFileBackwards(ByVal sFilePath As String, ByVal sSearchString As String)
    Dim i As Integer

    Dim streamTextFile As Stream

    streamTextFile = File.OpenRead(sFilePath)
    streamTextFile.Seek(0, SeekOrigin.End)

    Dim stringArray() As String
    Dim sBuffer As String = ""

    Dim iBlockSize As Integer = 41000
    Dim iFirstElement As Integer = 1

    While streamTextFile.Position > 0
      If streamTextFile.Position <= iBlockSize Then
        iBlockSize = CInt(streamTextFile.Position)
        iFirstElement = 0
      End If
      Dim byteArray(iBlockSize - 1) As Byte
      streamTextFile.Seek(-1 * iBlockSize, SeekOrigin.Current)
      streamTextFile.Read(byteArray, 0, byteArray.Length)
      streamTextFile.Seek(-1 * iBlockSize, SeekOrigin.Current)
      stringArray = Split(ASCII.GetString(byteArray), vbCrLf)
      stringArray(stringArray.Length - 1) = stringArray(stringArray.Length - 1) + sBuffer
      For i = stringArray.GetUpperBound(0) To iFirstElement Step -1
        'Do Your Check If The Line has something that requires your file to be changed
        ' eg: if stringArray(i) = "123456" do Bla Bla Bla
      sBuffer = stringArray(0)
    End While

  End Sub
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.