Results 1 to 32 of 32

Thread: [RESOLVED] Read last 200 lines of a text file

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Resolved [RESOLVED] Read last 200 lines of a text file

    I'm trying to read the last 200 lines of a text file - however the following returns a single line (line number 200 from the end of the file) instead of the last 200 lines

    Code:
     Dim lines As String() = IO.File.ReadAllLines(Strings.LogFile)
                logresults = lines.Length - 200
    How do i read the last 200 lines of the file?

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    try this:

    Code:
    Dim lines As String() = IO.File.ReadAllLines(Strings.LogFile)
    If lines.Length >= 200 Then
        lines = lines.Skip(lines.Length - 200).ToArray
    End If

  3. #3
    Wall Poster TysonLPrice's Avatar
    Join Date
    Sep 2002
    Location
    Columbus, Ohio
    Posts
    3,834

    Re: Read last 200 lines of a text file

    .paul beat me to it and that solution looks more elegant but I put this together. It needs tested a little more but since I spent the time doing it
    Code:
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim lines As String() = IO.File.ReadAllLines("C:\TestIt.txt")
            Dim iCount = lines.Length
    
            Dim iStart As Integer
            iStart = iCount - 199
    
            Dim strTextLine As String
    
            For i = iStart To iCount - 1
                strTextLine = System.IO.File.ReadAllLines("C:\TestIt.txt")(i)
            Next
    
        End Sub
    Please remember next time...elections matter!

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    Thanks guys, unfortunately i don't appear to be having much luck with either of these solutions

    Paul:i get an error using the following code:

    skip is not a member of system.array
    Code:
        ' Read last 200 lines of log file
        Public Function ReadLog() As String
            Dim lines As String() = IO.File.ReadAllLines(Strings.LogFile)
            If lines.Length >= 200 Then
                lines = lines.Skip(lines.Length - 200).ToArray
            End If
            Return lines.ToString
        End Function
    Tyson: your code has an error

    i is not declared
    So i presume it should be an integer and added it as below, but it only returns the line before last - not the whole last 200 lines

    Code:
           ' Read last 200 lines of log file
        Public Function ReadLog() As String
    
                Dim lines As String() = IO.File.ReadAllLines(Strings.LogFile)
                Dim iCount = lines.Length
            Dim i As Integer
    
                Dim iStart As Integer
                iStart = iCount - 199
    
                Dim strTextLine As String
    
                For i = iStart To iCount - 1
                    strTextLine = System.IO.File.ReadAllLines(Strings.LogFile)(i)
                Next
                Return strTextLine
    
        End Function

  5. #5
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    which version of vb.net are you using?

  6. #6
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    which version of vb.net are you using?

    it looks like you using vb2008. you need to be targeting 3.5 framework for LINQ

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    VS 2010 - however its compiled for .net 2.0 to maximize compatibility

  8. #8
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    ok. for .Net 2.0 compatibility:

    Code:
    Private Function getLast200Elements(Of T)(ByVal a() As T) As T()
        If a.Length <= 200 Then Return a
        Dim newArray(199) As T
        Array.Copy(a, a.Length - 200, newArray, 0, 200)
        Return newArray
    End Function

  9. #9
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Read last 200 lines of a text file

    VS 2010 - however its compiled for .net 2.0 to maximize compatibility
    I really doubt that there are many (if any) potential users of your program who do not already have or cannot install at least 3.5 but if you insist all yopu need to do to Tyson's solution is add a declaration for i (Dim i As Integer).
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  10. #10
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    Quote Originally Posted by dunfiddlin View Post
    I really doubt that there are many (if any) potential users of your program who do not already have or cannot install at least 3.5 but if you insist all yopu need to do to Tyson's solution is add a declaration for i (Dim i As Integer).
    Code:
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim lines As String() = IO.File.ReadAllLines("C:\TestIt.txt")
            Dim iCount = lines.Length
    
            Dim iStart As Integer
            iStart = iCount - 199
    
            Dim strTextLine As String
    
            For i = iStart To iCount - 1
                strTextLine = System.IO.File.ReadAllLines("C:\TestIt.txt")(i)
            Next
    
        End Sub
    really??? start at the wrong index, reread the file for every line, + not store those lines in an array??? I forgot you were such a great programmer

  11. #11
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Read last 200 lines of a text file

    Hey, I program gooder than most. I just don't read properer than, well, pretty much anybody!
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  12. #12

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    Quote Originally Posted by .paul. View Post
    ok. for .Net 2.0 compatibility:

    Code:
    Private Function getLast200Elements(Of T)(ByVal a() As T) As T()
        If a.Length <= 200 Then Return a
        Dim newArray(199) As T
        Array.Copy(a, a.Length - 200, newArray, 0, 200)
        Return newArray
    End Function
    Where would i put the location of the text file in this code?

    i.e. c:\logfile.txt

    I tried
    Code:
     Private Function getLast200Elements(Of T)(ByVal a("c:\logfile.txt") As T) As T()
    however this causes an error

    array bounds cannot appear in type specifiers

  13. #13
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    Dim lines() as String = IO.File.ReadAllLines("C:\logfile.txt")

    Dim newLines()as string = getLast200Elements(lines)

  14. #14
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Read last 200 lines of a text file

    It's a Function. You pass it a value and get a result back. Are you in the habit of adding extraneous details to Function definitions?

    Dim lines As String() = IO.File.ReadAllLines(Strings.LogFile)
    Dim lines200 = getLast200Elements(lines)
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    Sorry, i'm getting lost

    Code:
        ' Read last 200 lines of log file
        Public Function ReadLog() As String
            Dim lines As String() = IO.File.ReadAllLines(Strings.LogFile)
            Dim lines200 = getLast200Elements(lines)
            Return lines200.ToString
        End Function
    
        Private Function getLast200Elements(Of T)(ByVal a() As T) As T()
            If a.Length <= 200 Then Return a
            Dim newArray(199) As T
            Array.Copy(a, a.Length - 200, newArray, 0, 200)
            Return newArray
        End Function

  16. #16
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    how do you want the output? as an array of strings, or as a single string?

  17. #17

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    A single string i presume, i simply want to read the last 200 lines and return them using a single return command - e.g. return logfile

  18. #18

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    When i return the whole logfile using a single return command it comes out such as:

    27/12/2013 17:51:26Message: Application Started
    27/12/2013 17:51:27 Message: Network Check Started
    27/12/2013 17:51:51
    Error In:
    Line Number:0
    Error Message: Unable to connect to the remote server
    27/12/2013 17:51:51 Message: Internet Failed 1st Check
    27/12/2013 17:51:55 Message: Application Started
    27/12/2013 17:51:56 Message: Network Check Started
    27/12/2013 17:52:06 Message: Network Established
    27/12/2013 17:52:06 Message: Running Startup Checks
    27/12/2013 17:52:08 Message: Decompiling
    27/12/2013 17:52:08 Message: Compiling
    27/12/2013 17:52:08 Message: Startup Checks Complete..Loading Splash
    27/12/2013 17:52:10 Message: Splash Loaded
    27/12/2013 17:52:12

  19. #19
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    What do you intend to do with the returned value? If you're putting it in a textbox or just writing it to a new file, a string formatted with beeline characters would be ok

  20. #20
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    That should be newline + not beeline. Excuse my predictive typing

  21. #21

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    basically if a client has a support issue, the client runs a diagnostics report through the software which gets emailed to me via a httpwebrequest - i want to append the last 200 lines of the log file to the diagnostics report

  22. #22

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    I can return the whole logfile which i've tested successfully - however if the logfile gets big it will fail to send

  23. #23

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    This returns the whole logfile perfectly

    Code:
        Public Function ReadLog() As String
            If File.Exists(Strings.LogFile) Then
                Using tr As TextReader = New StreamReader(Strings.LogFile)
                    Return tr.ReadToEnd
                End Using
            End If
        End Function
    However i'm worried it will cause issues when the logfile gets large

  24. #24
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: Read last 200 lines of a text file

    Code:
    ' Read last 200 lines of log file
    Public Function ReadLog() As String
        Dim lines() As String = IO.File.ReadAllLines("C:\logfile.txt")
        If lines.Length <= 200 Then Return String.Join(Environment.NewLine, lines)
        Dim lines200(199) As String
        Array.Copy(lines, lines.Length - 200, lines200, 0, 200)
        Return String.Join(Environment.NewLine, lines200)
    End Function

  25. #25

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    Superb Paul

    Works a treat - many thanks for your help guys - it really is appreciated!!

  26. #26
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Read last 200 lines of a text file

    Use a StringBuilder ....

    vb.net Code:
    1. Dim sb As New System.Text.StringBuilder
    2.         sb.Append(DiagnosticReport) ' the text as a string
    3.         sb.AppendLine()
    4.  
    5.         Dim lines As String() = IO.File.ReadAllLines(Strings.LogFile)
    6.         Dim lines200 = getLast200Elements(lines)
    7.  
    8.         For each Ln in Lines200
    9.         sb.AppendLine(Ln)
    10.         Next
    11.  
    12.         Return sb.ToString
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  27. #27
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Read last 200 lines of a text file

    Or do it that way ... sigh! Must learn to type faster!
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  28. #28

    Thread Starter
    Addicted Member
    Join Date
    Feb 2009
    Location
    Uk
    Posts
    157

    Re: Read last 200 lines of a text file

    thanks dunfiddlin - Paul beat you to it - however i do appreciate your help!

    Many thanks

  29. #29
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: [RESOLVED] Read last 200 lines of a text file

    Ah yes, .paul beat me to it. They'll be writing that on my gravestone (I hope .... mwhaha!!!)
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  30. #30
    Wall Poster TysonLPrice's Avatar
    Join Date
    Sep 2002
    Location
    Columbus, Ohio
    Posts
    3,834

    Re: [RESOLVED] Read last 200 lines of a text file

    I'll look at it tomorrow morning. I did it right before I left for the day Friday but in the text file I had 252 lines. Displayed where it started and ended, I may have missed something. I wrote it on VS 2012. I will put out a tested version for you tomorrow morning (EST).
    Please remember next time...elections matter!

  31. #31
    Wall Poster TysonLPrice's Avatar
    Join Date
    Sep 2002
    Location
    Columbus, Ohio
    Posts
    3,834

    Re: [RESOLVED] Read last 200 lines of a text file

    I see it is resoved and my way was the clunkiest but I fixed the error and made testing easier (for me).

    Code:
    Dim lines As String()
            Dim iCount As Integer
            Dim Inputfile As System.IO.StreamWriter
            Dim Outputfile As System.IO.StreamWriter
            Dim iStart As Integer = 1
            Dim strTextLine As String
    
            If System.IO.File.Exists("C:\Input.txt") = True Then
                System.IO.File.Delete("C:\Input.txt")
            End If
    
            If System.IO.File.Exists("C:\Output.txt") = True Then
                System.IO.File.Delete("C:\Output.txt")
            End If
    
            Inputfile = My.Computer.FileSystem.OpenTextFileWriter("c:\Input.txt", True)
            Outputfile = My.Computer.FileSystem.OpenTextFileWriter("c:\Output.txt", True)
    
            Using Inputfile
                For i = 1 To 300
                    Inputfile.WriteLine(i)
                Next
            End Using
    
            lines = IO.File.ReadAllLines("C:\Input.txt")
            iCount = lines.Length
    
            iStart = iCount - 200
    
            For i = iStart To iCount - 1
                strTextLine = System.IO.File.ReadAllLines("C:\Input.txt")(i)
                Outputfile.WriteLine(strTextLine)
            Next
            Outputfile.Close()
        End Sub
    Please remember next time...elections matter!

  32. #32
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,297

    Re: [RESOLVED] Read last 200 lines of a text file

    Just for kicks, this could all be done in two lines:
    Code:
    Dim lines = IO.File.ReadAllLines("file path here")
    Dim text = String.Join(Environment.NewLine,
                           lines,
                           Math.Max(0, lines.Length - 200),
                           Math.Min(200, lines.Length))

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width