tags:

views:

52

answers:

3

In a application of mine that is developed in C# I have the following code:

byte[] resb = new byte[Buffer.ByteLength(blockAr) + Buffer.ByteLength(previous)];
Array.Copy(blockAr, 0, resb, 0, blockAr.Length);
Array.Copy(previous, 0, resb, blockAr.Length, previous.Length);

It's a very simple code to concatenate two byte arrays.

The problem is that in some particular situation that I don't know I have that exception:

ArgumentOutOfRangeException: sourceIndex is less than the lower bound of the first dimension of sourceArray.

I cannot see any of strange in my code and I am not able to reproduce the exception.

Could anyone help me to identify the problem?

thanks

+1  A: 

Could either blockAr or previous be an empty array? That would explain the exception, since even index 0 would be out of bounds.

Matti Virkkunen
No because when blockAr is empty (blockAr = {}) the srcIndex at 0 is good and I have no exceptions. I've seen that only in the case the index is a negative number I have the exception!!!!But the index is hardcoded in the source code!!!!!This is a very very strange thing!!!
robob
A: 

IDK but is there a reason to in the first line use ByteLength and then in the next line instead use Length? Maybe there is some nuance there that is causing inconsistency. Try using ByteLength in both places and then try using Length in both places, and see if one of them resolves your problem.

AaronLS
A: 

It wasn't the code I showed to you. The buggy code is: Convert.ToBase64String(byte[] array)....

It seems that ToBase64String internally uses Array.Copy and in particular situations raises the exception I pointed before. It is very strange that a Library function doesn't raise an its own exception.

To resolve the problem I have enclosed it in a try-catch statement, and now all works!

Thanks to all for the suggestion.

robob
Oh, so could you please close the question and/or set this as an accepted answer?
Ron Klein