Search code examples
c#stringencodingbytenon-printing-characters

Removing non Printable values aftert Encoding.ASCII.GetString()


Suppose I have a Byte array and I use Encoding.ASCII.GetString() to convert the bytes into a string. Now the first few bytes will contain actual values, but the remaining ones will all have value of 0. After obtaining the string, when I show it on a WPF Form, there are some non printable characters. How can I remove these non printable characters. One way would be to loop through the array and only consider up to an index not containing 0, but I may also Encode using Unicode, that is Encoding.Unicode.GetString().

What would be the most generic way to solve the problem.


Solution

  • var buffer = new byte[] { 65, 66, 67, 68, 0, 0, 0, 0, 0 };
    var length = buffer.TakeWhile(b => b != 0).Count();
    var text = Encoding.UTF8.GetString(buffer, 0, length);