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?

4 Answers 4

5

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

string base64String = Convert.ToBase64String(myByteArray);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes!. This is what i was looking for. Thank you. I'll accept your answer in 3 minutes
1

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

Comments

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

Comments

1

This is a simple form of doing it

string System.Text.Encoding.UTF8.GetString(YourbyteArray)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.