Andy
Andy

Reputation: 937

ASCIIEncoding and Lower Control Characters

I expected my test code:

string Test = ASCIIEncoding.ASCII.GetString(new byte[] { 0x01, 0x02, 0x03, 0x04 });

to return a string containing "????" however it doesn't. How can I get an ASCII encoding of a set of bytes where all the control characters and top-bit-set characters are converted to '?'?

Thanks, Andy

Update:

I guess my question should have been: How do I get StreamWriter to output only printable ASCII characters? I need to generate text files that will work with ancient programs that will freak out on control characters in the file.

Upvotes: 1

Views: 659

Answers (1)

user1693593
user1693593

Reputation:

There is no automatic conversion to ? per-se. Usually ? is a representation of unreadable chars imposed by a host program.

However, if your intention is to convert these so the user sees a ? instead, try this code:

string newStr = "";
foreach (char c in MyString) {
    if ((int.Parse(c) < 32)) {
        c = "?";
    }
    newStr = (newStr + c.ToString);
}

Upvotes: 1

Related Questions