Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5474
  • Last Modified:

get the last line in text file (vb.net)

i want to kow how to read the last string line in a text file ,then to compare that last line with a string text in a textbox i have , if they equal i dont write the text in the text box  in the file , else if not equal i have to write the text in the text box   after the last line in the text file
0
WDAFFA
Asked:
WDAFFA
  • 2
1 Solution
 
moseackCommented:
Taken from MSDN:
        ' Open the file to read from.
        Dim sr As StreamReader = File.OpenText(path)
        Dim s As String
        Do While sr.Peek() >= 0
            s = sr.ReadLine()
        Loop
        sr.Close()

Open in new window

0
 
WDAFFAAuthor Commented:
i need to know what (peek) do?
how to earse the last line? or write over it
then how to write at the end after the last line/
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Here is a different method:
        Dim fileName As String = "c:\someFile.txt"
        Dim lines As New List(Of String)
        lines.AddRange(System.IO.File.ReadAllLines(fileName))
 
        ' display the last line
        Dim lastLine As String = lines.Item(lines.Count - 1)
        MessageBox.Show("lastLine = " & lastLine)
 
        ' replace the last line (in memory)
        lines.Item(lines.Count - 1) = "new line here"
 
        ' add a line (in memory)
        lines.Add("line added to end")
 
        ' replace the original file
        System.IO.File.WriteAllLines(fileName, lines.ToArray)

Open in new window

0
 
moseackCommented:
I believe Idle_Mind's answer is more complete then mine.

"Peek" allow you to see what the next character in the stream is, but doesn't move the stream pointer forward.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.peek.aspx
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now