|
|
||||||
|
#1
|
|
|
|
|
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 |
|
|
|
#2
|
|
|
|
|
theres no function like "LastLine"...you have to read in each line and keep
track of where you are in the file |
|
#3
|
|
|
|
|
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 "Li Pang" wrote: [..] |
|
#4
|
|
|
|
|
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 [..] |
|
|
| Similar Threads | |
| remove line from excel file Hello. I'm Reading data from an excel (CSV) file with header row and its fine. Now I have a file with one more line in the start (above the header) and it giving me a lot of... |
|
| remove a line of a file Hi, I have the variable Line=adios. If I have this file (palabras) hola adios ahora And I want to remove the line "adios" and the file will be: |
|
| Remove a line from a text file I use a text file to hold information but I need to be able remove a line of data, I was wondering if this is possible I have tried to inforamtion on this without... |
|
| How to read a text file line by line and remove some line Can anyone please help me in writing the code in C++ : I want a read a file line by line,remove the lines which have length of a particular field in a line exceeding 63... |
|
| Remove a line from a text file Hi, I want to remove the last line in a text file. Anybody has an easy way to do so Thanks |
|
|
All times are GMT. The time now is 04:35 PM. | Privacy Policy
|