Given a System.Text.Encoding instance and a string, how can I determine programmatically if that string can be represented using that encoding?
I am working on a serialization library, and when writing a string, I need to know if the string can be written as-is, or if it needs to be escaped.
I looked into the members of Encoding, but none seems to provide that information. One option might be to somehow create an equivalent instance of Encoding, but with a custom EncoderFallback that would capture whether it has been used, then attempting to convert the string to bytes using the encoding. This seems a bit hacky and not very efficient, though.