Reputation:
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:
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
Upvotes: 1
Views: 403
Reputation: 74207
Maybe I'm missing something, but you're slurping in the entire file up front, so you already not how big the output buffer needs to be. Ergo, this should do you just fine:
private static void better_copy( ushort blockSize )
{
if ( blockSize < 1 ) throw new ArgumentOutOfRangeException("blockSize") ;
byte[] input = File.ReadAllBytes( @"C:\Project1.exe" ); // 16,384 bytes
byte[] output = new byte[ input.Length] ;
for ( int p = 0 , n = 0 ; p < input.Length ; p += n )
{
int octetsRemaining = input.Length - p ;
n = ( octetsRemaining < blockSize ? octetsRemaining : blockSize ) ;
Array.Copy( input , p , output , p , n ) ;
}
File.WriteAllBytes( @"C:\blank.exe" , output );
return ;
}
Upvotes: 0
Reputation: 7426
Like competent_tech said, you don't want to recreate the test array each time.
I'm not totally sure about this, but why not initialize byte[] test = null;
to byte[] test = sData.Length;
and remove test = new byte[block.Length + pos];
from the loop?
Upvotes: 0
Reputation: 44931
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.
Upvotes: 1