"The parameter is incorrect" when installing Unicode as a console encoding

I get the following error:

Unhandled Exception: System.IO.IOException: The parameter is incorrect. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.__Error.WinIOError() at System.Console.set_OutputEncoding(Encoding value) at (my program) 

when I run the following line of code:

  Console.OutputEncoding = Encoding.Unicode; 

Any idea why? I do not get this error if instead I set the encoding to UTF8.

+6
c # encoding
source share
3 answers

Encoding.Unicode is UTF-16, which uses 2 bytes to encode all characters. ASCII characters (English characters) are the same in UTF-8 (single bytes, same values), so it is possible that this works.

I assume that the Windows Command Shell does not fully support Unicode. It's funny that the Powershell 2 GUI supports UTF-16 (as far as I know), but the program throws an exception there.

The following code works, which shows that the Console object can redirect its output and support Encoding.Unicode:

 FileStream testStream = File.Create("test.txt"); TextWriter writer = new StreamWriter(testStream, Encoding.Unicode); Console.SetOut(writer); Console.WriteLine("Hello World: \u263B"); // unicode smiley face writer.Close(); // flush the output 
+3
source share

According to the list of Code Page Identifiers in MSDN, the UTF-16 and UTF-32 encodings are only managed:

 1200 utf-16 Unicode UTF-16, little endian byte order (BMP of ISO 10646); available only to managed applications 1201 unicodeFFFE Unicode UTF-16, big endian byte order; available only to managed applications 12000 utf-32 Unicode UTF-32, little endian byte order; available only to managed applications 12001 utf-32BE Unicode UTF-32, big endian byte order; available only to managed applications 

For example, they are not listed in the registry with other system code pages in the HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Nls \ CodePage section.

+1
source share

I think this is due to the CodePage used by Encoding . In particular, see SetConsoleOutputCP Function . I don’t know much more, sorry.

Edit: I provided a link to SetConsoleOutputCP because this function is internally called (via PInvoke) using (setting the operation) Console.OutputEncoding .

0
source share

All Articles