This is more for practice than anything, really. I am having the most frustrating time with this as it’s a fairly new concept to me. I will post my code below.
What I am attempting to do:
- Read a file into a byte array
- Split the byte into pars of a predefined size
-
Put the parts back together, and write the file to HD
byte[] sData = File.ReadAllBytes(@”C:\Project1.exe”); // 16,384 bytes
// Split the data up here int range = 8; range *= 1024; int pos = 0; int remaining; int i = 0; byte[] test = null; while ((remaining = sData.Length - pos) > 0) { byte[] block = new byte[Math.Min(remaining, range)]; test = new byte[block.Length + pos]; Array.Copy(sData, pos, test, pos, block.Length); pos += block.Length; i++; } File.WriteAllBytes(@"C:\blank.exe", test);
The file “blank.exe” is always corrupt.
Does anyone see my error(s) here?
I appreciate it, Evan
You are recreating the test array on each pass through the loop.
This means when you write the test array to the file at the end, you are only writing the last block of data that you processed.
You have a few options:
1) Resize the array on each pass and copy the previous data into the new array. This would be very inefficient. This is the same mechanism that Array.Resize uses.
2) If you know the desired size of the array ahead of time (i.e. it is the same size as the data you read from the file or a multiple of the file size), then just resize the array one time before entering the loop.
3) Use a different data structure, such as as List or an ArrayList.