简体   繁体   中英

Converting a byte array to string and back in C#

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.

Use this:

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM