public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count)
{
if (!ValidateUrlEncodingParameters(value, offset, count))
{
return null;
}
bool foundSpaces = false;
int unsafeCount = 0;
// count them first
for (int i = 0; i < count; i++)
{
char ch = (char)value[offset + i];
if (ch == ' ')
foundSpaces = true;
else if (!IsUrlSafeChar(ch))
unsafeCount++;
}
// nothing to expand?
if (!foundSpaces && unsafeCount == 0)
{
var subarray = new byte[count];
Buffer.BlockCopy(value, offset, subarray, 0, count);
return subarray;
}
// expand not 'safe' characters into %XX, spaces to +s
byte[] expandedBytes = new byte[count + unsafeCount * 2];
GetEncodedBytes(value, offset, count, expandedBytes);
return expandedBytes;
}