How to read/write a file in binary mode

Cyrus

Member
Joined
Jul 25, 2003
Messages
11
Im currently trying to develop some kind of file-transfer tool.
so i have to read a file completely in binary mode, transfer it, and write it again on the other computer.

but i have the following problem: how do i know when the filestream ends?

this code is working, but i am looking for a "better" one:

Code:
  Private Sub ReadWrite()
    Dim Input As New System.IO.BinaryReader(New IO.FileStream("d:\auth.dll", IO.FileMode.Open))
    Dim Output As New System.IO.BinaryWriter(New IO.FileStream("d:\auth2.dll", IO.FileMode.Create))
    Dim t As Byte

    While True
      Try
        t = Input.ReadByte
        Output.Write(t)
      Catch ex As System.IO.EndOfStreamException
        Exit While
      End Try
    End While
    Input.Close()
    Output.Close()
  End Sub

has anyone suggestions?

thanks,

Cyrus
 
you could bung it all in to a byte array in 1 go like this...
Code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim bReader As New IO.BinaryReader(New IO.FileStream("D:\dao.dll", IO.FileMode.Open))
        Dim bWriter As New IO.BinaryWriter(New IO.FileStream("C:\dao.dll", IO.FileMode.Create))
        Dim bt As Byte()
        Try

            bt = bReader.ReadBytes(bReader.BaseStream.Length) /// fill the byte array bt() with the chunk of data.
            bWriter.Write(bt)

            bReader.Close()
            bWriter.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
but why not use filecopy?, in one line...
Code:
IO.File.Copy("C:\dao.dll", "D:\dao.dll")
 
why not filecopy? because it should be transfered per TCP/IP later.... this is just a "test" how to read a file completely binary and write it again...

bt = bReader.ReadBytes(bReader.BaseStream.Length)
bWriter.Write(bt)

does this also work if the file is huge!? for example 1000 MB? i dont think so :(
 
Back
Top