0

I am reading a file into a byte array and converting the byte array into a string to pass into a method(I cant pass the byte array itself) and in the function definition I am reconverting the string to byte array. but both the byte arrays( before and after conversion are different)

I am using the following pilot code to test if byte arrays are same.

byte[] bytes = File.ReadAllBytes(@"C:\a.jpg");
 string encoded = Convert.ToBase64String(bytes);
byte[] bytes1 = Encoding.ASCII.GetBytes(encoded);

When I use bytes in the api call, it succeds and when I use bytes1 it throws an exception. Please tell me how can I safely convert the byte array to string and back such that both arrays reman same.

Rishabh Jain
  • 41
  • 1
  • 2
  • 11

2 Answers2

5

Use this:

byte[] bytes = File.ReadAllBytes(@"C:\a.jpg");
string encoded = Convert.ToBase64String(bytes);
byte[] bytes1 = Convert.FromBase64String(encoded);
Asad Ali
  • 684
  • 6
  • 17
0

I'll post a response from another thread:

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);
}

full thread here: How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

Community
  • 1
  • 1
Adrian Toma
  • 547
  • 2
  • 13