簡體   English   中英

在C#中將字節數組轉換為字符串並返回

[英]Converting a byte array to string and back in C#

我正在將文件讀入字節數組並將字節數組轉換為字符串以傳遞給方法(我無法傳遞字節數組本身),並且在函數定義中我將字符串重新轉換為字節數組。 但兩個字節數組(轉換前后不同)

我使用以下導頻代碼來測試字節數組是否相同。

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

當我在api調用中使用字節時,它成功了,當我使用bytes1時,它會拋出異常。 請告訴我如何安全地將字節數組轉換為字符串並返回,以便兩個數組重新相同。

用這個:

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#中獲得字符串的一致字節表示?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM