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

后端 未结 15 2352
迷失自我
迷失自我 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:55

    A general solution to convert from byte array to string when you don't know the encoding:

    static string BytesToStringConverted(byte[] bytes)
    {
        using (var stream = new MemoryStream(bytes))
        {
            using (var streamReader = new StreamReader(stream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
    

提交回复
热议问题