Search code examples
c#.netbinaryreaderbinarywriter

Get Encoding of BinaryReader/Writer?


The .NET BinaryReader/BinaryWriter classes can be constructed with specifying an Encoding to use for String-related operations.

I was implementing custom string formats with extension methods, but would yet implement them in a way they respect the Encoding specified when instantiating the BinaryReader/Writer.

There does not seem to be a way to retrieve the Encoding from the reader/writer, not even when inheriting from their class. I could only inherit from them to intercept the passed encoding by recreating all their constructors. I looked into the .NET source code, and it is only used to instantiate a Decoder class (in case of the BinaryReader), but I can't access that one also.

Do I lose to a shortcoming in those classes here? Can I hack into them with reflection?


Solution

  • If subclassing and intercepting the Encoding in the constructors is even remotely feasible in your scenario, I'd prefer it over potentially unstable reflection hacks.

    However, if you must go the reflection route for some reason, here are some pointers I found from the BinaryReader source code you referenced: