ASCIIEncoding and Error Detection

Henri Hein 21 Reputation points
2021-10-06T21:38:19.593+00:00

The documentation for ASCIIEncoding in the .Net library states:

ASCIIEncoding does not provide error detection. For security reasons, you should use UTF8Encoding, UnicodeEncoding, or UTF32Encoding and enable error detection.

In my application, I don't want to use the Unicode encodings, as I need to process characters byte by byte and only convert ASCII compatible characters. For instance, I need to see 0xC2A9 as 0xC2 and 0xA9, not as the copyright symbol. I want to use ASCIIEncoding with the EncoderFallback property, but the above note has me worried. What exactly does "not provide error detection" mean? I assume it has to do with buffer overflow. Is there a way to manually add the needed error detection, or should I bite the bullet and write my own Encoder class? TIA.

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,131 questions
0 comments No comments
{count} votes

Accepted answer
  1. Xingyu Zhao-MSFT 5,356 Reputation points
    2021-10-07T01:36:05.493+00:00

    Hi @Henri Hein ,
    In UTF8Encoding Class Document:
    138371-1.png

    With error detection enabled, a method that detects an invalid sequence of characters or bytes throws an ArgumentException exception. Without error detection, no exception is thrown, and the invalid sequence is generally ignored.

    So if you want to use ASCIIEncoding class, you need to manually throws an ArgumentException exception when an invalid sequence of characters or bytes occurs.

    Hope it could be helpful.

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful