在c#中转换字节数组和字符串

本文关键字:数组 字符串 字节数 字节 转换 | 更新日期: 2023-09-27 18:04:01

我正在将文件读取为字节数组并将字节数组转换为字符串以传递给方法(我不能传递字节数组本身),并且在函数定义中我正在将字符串重新转换为字节数组。但是两个字节数组(转换前后是不同的)

我使用下面的先导代码来测试字节数组是否相同。

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

当我在api调用中使用bytes时,它成功,当我使用bytes1时,它抛出异常。请告诉我如何安全地将字节数组转换为字符串并返回,使两个数组保持相同。

在c#中转换字节数组和字符串

使用

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

我将发布另一个线程的响应:

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);
}
我如何在c#中获得一致的字符串字节表示而不手动指定编码?