VB.NET Delete all bytes after a specific one in a file

256 Views Asked by At

in my VB.NET program I have to delete all bytes that come after these ones: 48534853 untill it's end (I know that this will corrupt the file).

How can I do that? I already wrote functions to replace a pattern with another one and to locate specific bytes, but I don't know how to wipe out everything after a pattern.

1

There are 1 best solutions below

3
On

Use the FileStream.SetLength method.

Using stream = New FileStream(path, FileMode.Open, FileAccess.Write)
    fileStream.SetLength(newLength)
End Using

--

Try this:

Dim pattern As Integer() = New Integer() {&H48, &H53, &H48, &H53}
Dim p As Integer = 0 'Position in pattern.
Using fs = New FileStream("path", FileMode.Open, FileAccess.ReadWrite)
    For pos As Integer = 0 To fs.Length - 1
        Dim b As Integer = fs.ReadByte()
        If b = pattern(p) Then
            p += 1
            If p = pattern.Length Then
                fs.SetLength(pos - pattern.Length + 1)
                Return
            End If
        Else
            p = 0
        End If
    Next
End Using

Note that fs.ReadByte() returns the byte as Integer.