Ciao,
dalle specifiche per un web service mi viene richiesto di restituire il contenuto di un documento (che risede sul DB dell'azienda) in formato binario base64, ricevendo come parametro di ingresso il relativo ID.
Al momento uso il seguente codice, che restituisce una stringa base64.
Volevo chiedervi se il procedimento fosse corretto e se restituire una stringa fosse conforme alle specifiche (anzichè restituire array di byte base64).
Grazie in anticipo
static public string ToBase64( byte[] data )
{
int length = data == null ? 0 : data.Length;
if (length == 0)
return String.Empty;
int padding = length % 3;
if (padding > 0)
padding = 3 - padding;
int blocks = (length - 1) / 3 + 1;
char[] s = new char[blocks * 4];
for (int i = 0; i < blocks; i++)
{
bool finalBlock = i == blocks - 1;
bool pad2 = false;
bool pad1 = false;
if (finalBlock)
{
pad2 = padding == 2;
pad1 = padding > 0;
}
int index = i * 3;
byte b1 = data[index];
byte b2 = pad2 ? (byte)0 : data[index + 1];
byte b3 = pad1 ? (byte)0 : data[index + 2];
byte temp1 = (byte)((b1 & 0xFC) >> 2);
byte temp = (byte)((b1 & 0x03) << 4);
byte temp2 = (byte)((b2 & 0xF0) >> 4);
temp2 += temp;
temp = (byte)((b2 & 0x0F) << 2);
byte temp3 = (byte)((b3 & 0xC0) >> 6);
temp3 += temp;
byte temp4 = (byte)(b3 & 0x3F);
index = i * 4;
s[index] = SixBitToChar( temp1 );
s[index+1] = SixBitToChar( temp2 );
s[index+2] = pad2 ? "=" : SixBitToChar( temp3 );
s[index+3] = pad1 ? "=" : SixBitToChar( temp4 );
}
return new string( s );
}
static private char SixBitToChar( byte b )
{
char c;
if (b < 26)
{
c = (char)((int)b + (int)'A');
}
else if (b < 52)
{
c = (char)((int)b - 26 + (int)'a');
}
else if (b < 62)
{
c = (char)((int)b - 52 + (int)'0');
}
else if (b == 62)
{
c = s_CharPlusSign;
}
else
{
c = s_CharSlash;
}
return c;
}
static private char s_CharPlusSign = '+';
static private char s_CharSlash = '/';
static public char CharPlusSign
{
get
{
return s_CharPlusSign;
}
set
{
s_CharPlusSign = value;
}
}
static public char CharSlash
{
get
{
return s_CharSlash;
}
set
{
s_CharSlash = value;
}
}