ymourok4
ymourok4

Reputation: 1

Changing bytes in existing binary file

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim OFD As New OpenFileDialog
    Try
        OFD.Filter = "Binary files (*.bin)|*.bin"
        If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
            fullFile = File.ReadAllBytes(OFD.FileName)

            Dim writer As New BinaryWriter(OFD.OpenFile)
            writer.Seek(&H5B0, SeekOrigin.Begin)
            writer.Write(CUShort(&HB1AA))
            writer.Close()
        End If

    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error")
    End Try

It should open file and then change bytes into it. But while open file I got message box with:

Error Can't write in stream

And file is still not changed. Fix my code.

Upvotes: 0

Views: 417

Answers (1)

Hans Passant
Hans Passant

Reputation: 942207

From the MSDN article about the OpenFileDialog.OpenFile() helper method:

Opens the file selected by the user, with read-only permission.

Relevant phrase bolded, that means you cannot write to the file. You need to use FileStream instead. Like this:

    If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
        Using fs As New FileStream(OFD.FileName, FileMode.Open, FileAccess.Write, FileShare.None)
            Using writer As New BinaryWriter(fs)
                writer.Seek(&H5B0, SeekOrigin.Begin)
                writer.Write(CUShort(&HB1AA))
            End Using
        End Using
    End If

Upvotes: 1

Related Questions