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
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.