I've observed, using Visual studio 2008 (with .NET 3.5), that the the value of Console.Out.Encoding
changes based upon if running via a debugger and Console App/Windows App in the following way:
- GUI App - using debugger
- System.Text.SBCSCodePageEncoding
- GUI App - not using a debugger
- System.Text.UTF8Encoding
- Console App - using a debugger
- System.Text.SBCSCodePageEncoding
- Console App - not using a debugger
- System.Text.SBCSCodePageEncoding
Now when Console.Out.Encoding
is set to SBCSCodePageEncoding
it doesn't throw exceptions when invalid utf16 surrogates written to it. For example:
string invalidStringContiaingHighOrderSurrogateWithOutMatchingLowOrderSurrogate = '\uD81B'.ToString() + ";";
Console.WriteLine(invalidStringContiaingHighOrderSurrogateWithOutMatchingLowOrderSurrogate);
Console.Out.Flush();
However when Console.Out.Encoding
is set to System.Text.UTF8Encoding
writing invalid utf16 surrogates to it throws System.Text.EncoderFallbackException
.
I want to be a able to ignore EncoderFallbackExceptions without having to add a try catch block to each use of Console.Out
in the large windows application I working with. How can I do this?
- Changing to a console app is NOT an acceptable solution.
- Somehow changing Console.Out.Encoding to SBCSCodePageEncoding IS a acceptable solution.
- I can't change Console.Out.Encoding.EncoderFallback as I get the following exception
System.InvalidOperationException
"Instance is readonly" - The win32 function SetConsoleOutputCP seemed to have no effect on my GUI/Windows app.
Use the
Console.OutputEncoding
property to set the encoding however you want.(Personally I'd stick with UTF-8, but create an
UTF8Encoding
, setting an appropriateEncoderFallback
value, e.g.ReplacementFallback
.)