2

This is my code:

byte[] base64String = //this is being set properly
var base64CharArray = new char[base64String.Length];
Convert.ToBase64CharArray(base64String,
                          0,
                          base64String.Length,
                          base64CharArray,
                          0);
var Base64String = new string(base64CharArray);

When i run this, I get the following error when calling Convert.ToBase64CharArray:

Either offset did not refer to a position in the string, or there is an insufficient length of destination character array. Parameter name: offsetOut

How do i fix this, so i can convert my byte array to a string, or is there a better way to convert a byte array to a string?

Kijewski
  • 25,517
  • 12
  • 101
  • 143
BoundForGlory
  • 4,114
  • 15
  • 54
  • 81

4 Answers4

5

Why do you need the char array? Just convert your byte[] directly to a Base64 string:

string base64String = Convert.ToBase64String(myByteArray);
Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

base64 encoding needs 4 characters to encode 3 bytes of input. you have to enlarge your output array.

Arne
  • 2,106
  • 12
  • 9
1

here is one way you can convert byte array to string

static byte[] GetBytes(string str) 
{ 
    byte[] bytes = new byte[str.Length * sizeof(char)]; 
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); 
    return bytes; 
} 

static string GetString(byte[] bytes) 
{ 
    char[] chars = new char[bytes.Length / sizeof(char)]; 
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); 
    return new string(chars); 
} 

you don't really need to worry about encoding.

more details can be found here

Community
  • 1
  • 1
Mayank
  • 8,777
  • 4
  • 35
  • 60
1

This is a simple form of doing it

string System.Text.Encoding.UTF8.GetString(YourbyteArray)
Jesus
  • 631
  • 3
  • 13