How to convert UTF-8 byte[] to string?

后端 未结 15 2338
迷失自我
迷失自我 2020-11-22 03:11

I have a byte[] array that is loaded from a file that I happen to known contains UTF-8.

In some debugging code, I need to convert it to a string. Is

15条回答
  •  花落未央
    2020-11-22 03:37

    Converting a byte[] to a string seems simple but any kind of encoding is likely to mess up the output string. This little function just works without any unexpected results:

    private string ToString(byte[] bytes)
    {
        string response = string.Empty;
    
        foreach (byte b in bytes)
            response += (Char)b;
    
        return response;
    }
    

提交回复
热议问题