Search code examples
vb.netfilecarriage-return

Removing CR/LF at end of file in VB.net


I've searched for a solution to this, but any I've found are either doing much more than I need or are not exactly what I want.

I have files I want to append to. I need to append to the end of the last line but they all have a carriage return and so I'll end up appending to the new line if I just append as normal.

All I want is to make a subroutine that takes a file path and removes the CR/LF at the end of it, no more, no less. Any help pointing me at a solution to this would be appreciated. I'm surprised there isn't a built in function to do this.


Solution

  •     Dim crString = Environment.NewLine '= vbCrLf
        Dim crBytes = Encoding.UTF8.GetBytes(crString)
        Dim bytesRead(crBytes.Length -  1) as Byte
        Dim iOffset As Integer = 0
        Dim stringRead As String 
    
        Using fs = File.Open("G:\test.txt", FileMode.Open, FileAccess.ReadWrite)      
            While iOffset < fs.Length    
                fs.Seek(- (crBytes.Length + iOffset), SeekOrigin.End)
                fs.Read(bytesRead,0, crBytes.Length)
                stringRead = Encoding.UTF8.GetString(bytesRead)
                If stringRead = crString Then
                    fs.SetLength(fs.Length - (crBytes.Length  * iOffset + 1))
                    Exit While
                 End If
                iOffset += 1
            End While
        End Using
    

    I open the text file as FileStream and set its position to the end of the file - length of the carriage return string.

    I then read the current bytes while decreasing the offset until I found a carriage return or the eof has been reached.

    If a CR has been found I remove it and everything what comes after. If you don´t want that just remove the loop and check the eof only. But there could be some vbNullString at the eof that´s why I´m using the loop.

    Please note that I used UTF8 encoding in my example. If you have other encodings you have to adapt it accordingly.

    test.txt before run:

    Before

    test.txt after code snippet run:

    enter image description here

    EDIT: fs.SetLength part was wrong in case of last character in file was not a CR.