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?

kay
  • 24,516
  • 10
  • 94
  • 138
BoundForGlory
  • 3,981
  • 12
  • 47
  • 73

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
  • 159,022
  • 53
  • 345
  • 499
1

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

Arne
  • 2,096
  • 11
  • 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,641
  • 4
  • 34
  • 58
1

This is a simple form of doing it

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