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

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

    A Linq one-liner for converting a byte array byteArrFilename read from a file to a pure ascii C-style zero-terminated string would be this: Handy for reading things like file index tables in old archive formats.

    String filename = new String(byteArrFilename.TakeWhile(x => x != 0)
                                  .Select(x => x < 128 ? (Char)x : '?').ToArray());
    

    I use '?' as default char for anything not pure ascii here, but that can be changed, of course. If you want to be sure you can detect it, just use '\0' instead, since the TakeWhile at the start ensures that a string built this way cannot possibly contain '\0' values from the input source.

提交回复
热议问题