kegs88
kegs88

Reputation: 37

How to truncate the last portion of a large text file

I'm trying to strip out the last ^ and line-feed at the end of a file. This code works great for small files, but not for very large ones. I was considering reading the file in chunks or perhaps just the last portion, but I'm not sure how to do that.

Dim text As String
Dim intLength As Integer
Dim strEnd As String

text = File.ReadAllText(pstrOutputFolder & "tblzTF2FORMS_" & pstrFormType & ".txt")
intLength = Len(text)
strEnd = Right(text, 2)
If strEnd = "^" & vbLf & "" Then
    intLength = intLength - 2
    text = Left(text, intLength)
    File.WriteAllText(pstrOutputFolder & "tblzTF2FORMS_" & pstrFormType & ".txt", text)
End If

Upvotes: 1

Views: 184

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

Reading the whole file in chunks, progressively writing all the data to a second temporary file (except the last two characters, of course) is going to be your best bet. When you're using a FileStream, it is possible to seek to a given position and then overwrite individual bytes, but that only works when you are overwriting the data with new data of the same length. That doesn't work when you are truncating.

Upvotes: 1

Related Questions