How to remove last line in a file

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I want to know the easiest way to remove the last line in a text file, or
how to catch the last line of a text file. Thanks in advance
 
theres no function like "LastLine"...you have to read in each line and keep
track of where you are in the file
 
I built the function by myself as below:

Function RemoveNLinesFromFile(ByVal _Filename As String, ByVal
_LinesToRemove As Integer) As String

Dim f As FileStream
Dim CurrentPosition
Dim LinesFound As Integer = 0
Dim rval As String = ""
Dim ch As Byte

Try

f = File.Open(_Filename, FileMode.Open)
CurrentPosition = f.Length - 1

While (CurrentPosition >= 0 And LinesFound < _LinesToRemove)
f.Position = CurrentPosition
ch = f.ReadByte()
'rval += Convert.ToChar(s.ReadByte)
'Debug.WriteLine("Position: " & s.Position & ", Value: " &
Convert.ToChar(s.ReadByte))
If ch = 13 Then 'line feed
LinesFound += 1
If LinesFound >= _LinesToRemove Then
Exit While
End If
Else
If LinesFound < 1 Then
'Debug.WriteLine(Convert.ToChar(ch))
rval = CStr(Convert.ToChar(ch)) + rval
End If
End If
CurrentPosition -= 1
End While

If CurrentPosition < 0 Then
'MsgBox("Not enough lines in file to remove " &
_LinesToRemove & " lines, only found " & LinesFound & " lines")
rval = "FAILED"
Else
f.SetLength(CurrentPosition + 2)
End If
Catch ex As Exception
Return "FAILED" & ex.Message
Finally
f.Close()
End Try

If rval <> "FAILED" Then
rval = Mid(rval, 2, Len(rval))
End If

Return rval

End Function
 
Hello Li,

Wow. That's a lotta code just to remove a couple lines. Plus it will only
work on ascii encoded files.
Try reading the entire file in, split the text on newline chars, then join
the lines back together using String.Join. Not super efficient but the code
is easy to read and maintain. If speed or memory consumption becomes an
issue you can look into optimization techniques.

-Boo
 
Back
Top