Brian Sweeney
Brian Sweeney

Reputation: 6793

Unable to set DecoderFallback property of an Encoding type

I'm attempting to set the DecoderFallback property of an arbitrary (but supported) encoding in my C# app. Essentially what i'm trying to do is this:

ASCIIEncoding ascii = new ASCIIEncoding();
ascii.DecoderFallback = new DecoderExceptionFallback();

I'm getting an exception i've never seen before:

System.InvalidOperationException was unhandled Message="Instance is read-only." Source="mscorlib"
StackTrace: at System.Text.Encoding.set_DecoderFallback(DecoderFallback value) at <... into my app...> InnerException:

I was unable to find any MSDN documenation with examples of how to use that property. If anyone could point me to some maybe suggest what is wrong my usage I'd appreciate it. I need to throw an exception upon failure to decode a byte or bytes and cannot afford to let that go unnoticed.

Thanks, brian

Upvotes: 5

Views: 1963

Answers (2)

palhares
palhares

Reputation: 1823

This property is read-only. You need to use Encoding.GetEncoding() to create your own encode with your configs. This method receive the encode, the EncoderFallback and the DecoderFallback.

var enc = System.Text.Encoding.GetEncoding("ASCII", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);

http://msdn.microsoft.com/pt-br/library/89856k4b.aspx

Upvotes: 6

alex2k8
alex2k8

Reputation: 43214

Based on http://www.google.com/codesearch?q=DecoderFallback

ASCIIEncoding ascii = (ASCIIEncoding)new ASCIIEncoding().Clone();
ascii.DecoderFallback = new DecoderExceptionFallback();

Upvotes: 0

Related Questions