Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading text file, bottom up??? 1

Status
Not open for further replies.

meinhunna

Programmer
Jul 31, 2004
118
0
0
AU
I have tab delimited text file which gets populated on daily basis via automated process. New entry is written at the bottom. I need to create a utility which makes a copy of this file with 10 most recent entries.

When I read line using StreamReader object it starts from the top, so looping though lines and keeping track of the line is not helpful. Is there anyway to start reading from the bottom or if anyone could suggest some other way???

Thanks
 
One way is to create a Datatable with just 2 fields in it, one being the line count of the file being imported and the second being the text line of the file itself. Once you have the file into a Datatable you can manipulate it much as you want to. In this case a simple descending sort on the line counter gives the file in reverse order.
Code:
'Declare Type Vars
Public Shared iType As Type = Type.GetType("System.Int32")
Public Shared sType As Type = Type.GetType("System.String")

'Create Table
Dim dt as new DataTable
dt.columns,add("iCounter",iType)
dt.columns.add("sLine",sType)

'Scan File
oFileContents = File.OpenText(sFileName)
dim iLoop as Integer=0
While oFileContents.Peek > 0
    Dim vals() As Object = New Object(1) {}

    sLine = oFileContents.ReadLine.TrimStart.TrimEnd
    vals(0)=iLoop
    vals(1) = sLine
    Me.oDataTable.Rows.Add(vals)
    iLoop+=1

End While

'Get DataTable in Reverse Order
dim drows as Datarow() 
drows = dt.select("","iCounter desc")
for each r as Datarow in drows
     'Your Code Here
next

Code untested...but it should be close enough



Sweep
...if it works dont mess with it
 
Or you can code the following, and the resulting array will contain your file "bottom up".
Code:
        Dim strReads As String
        Dim file As New System.IO.StreamReader("C:\YourFile.txt")
        While Not file.Peek() = -1
            strReads = file.ReadLine() & vbCrLf & strReads
        End While
        file.Close()

__________________________________________
Try forum1391 for lively discussions
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top