-
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();
-
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.