mayur patki
mayur patki

Reputation: 381

Deleting certain bytes from a text file after reading them in vb.net

i have written raw data (HEX characters) to text file.I want to retrieve mp3 information stored in the form of raw data in this text file after the text string MP3 start up till mp3 end.I have completed this operation but the problem now is the text contains many mp3 start and mp3end strings between which the mp3 characters are available.My program just extracts the characters between the first mp3 start and mp3 end string.After extarcting this information i want to delete this information from the file so that my program can extract the next set of mp3 characters.Is there any efficient way to do it.I am working on vb.net

Upvotes: 2

Views: 815

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

That depends. If the file format allows items to be blanked out and left with a blank "page", then that would be the most efficient option. However, if you must actually remove a section and shift up everything that comes after it, the only option is to rewrite the entire file.

Since you mentioned in the comments below that you do need to shift the rest of the file up to reduce the file size, your only option is to overwrite the entire file. Without knowing more specifics about your code, it's hard to say how best to do that, but the simplest method would look something like this:

Dim bytes() As Byte = File.ReadAllBytes(filePath)
' Modify and resize the bytes array
File.WriteAllBytes(filePath)

However, if the file is very large, you may not want to load the entire thing into memory all at once. In that case, it would be better to read in one segment at a time, and append each segment to a separate new the file in a loop. Then, when you are done copying all the desired data to the new file, you would need to rename it to overwrite the original file. For instance, something like this:

Using input As New FileStream(inputFilePath, FileMode.Open)
    Using output As New FileStream(tempFilePath, FileMode.Create)
        Dim bytes(lengthOfMp3Record) As Byte
        Dim totalRead As Integer = 0
        Do
            totalRead = input.Read(bytes, 0, bytes.Length)
            If (totalRead <> 0) AndAlso (KeepMp3record(bytes)) Then
                output.Write(bytes, 0, totalRead)
            End If
        Loop While totalRead <> 0
    End Using
End Using
File.Delete(inputFilePath)
File.Move(tempFilePath, inputFilePath)

Upvotes: 0

Related Questions