Results 1 to 2 of 2

Thread: binary file copy

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    binary file copy

    I know there is a File.Copy() function in .NET which is cool but just for my knowledge, I want to create a file copier from scratch.

    I thought I had this but I guess not....

    basically any file I try to copy, turns out to be larger in size than the original. Any ideas?

    Code:
    FileStream theFS = new FileStream(file, FileMode.Open);
    BinaryReader theReader = new BinaryReader(theFS);
    MemoryStream ms = new MemoryStream();
    int bytesRead = 0;
    byte[] buffer = new byte[500];
    
    while ((bytesRead = theReader.Reader(buffer, 0, buffer.Length)) != 0)
    {
       ms.Write(buffer, 0, bytesRead);
    }
    
    theFS.Close();
    theReader.Close();
    
    ms.Position = 0;
    
    FileStream fs = new FileStream("copy.exe", FileMode.Create);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.Write(ms.GetBuffer());
    bw.Close();
    fs.Close();
    ms.Close();

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  2. #2

    Thread Starter
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    Re: binary file copy

    well I guess I got it.
    had to add another int variable to keep track of how many total number of bytes we read, then when writing back to the destination file, write the bytes from the buffer, starting at index 0 for the length of the total amount read.

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width