How to Convert byte [] to string in C#

Ok, well first, the title of this post is deceiving. Really this post is about converting a byte array to a printable/displayable string in C#. The problem is that if you have an arbitrary byte array, say, representing an object from a stream or something, it may contain characters that are not actually printable or visible (i.e control characters) and when you try to use Console.WriteLine or anything of the sort, you may hear beeps or see weird shapes.

Anyway, I was coding a tool that allows inspection of objects in an MSM queue, and as such needed to somehow display a binary object. I wanted to do something similar to the Visual Studio Memory Watch debug window, where I showed the bytes that were “showable” and substituted a period (‘.’) for bytes that were not. Easy enough, here is the code snippet:

public string ConvertBytesToString(byte[] bytes)
    StringBuilder byteString = new StringBuilder("");
    foreach (Char e in bytes)                                                
        if (Char.IsControl(e))
    return byteString.ToString();