设置Unicode作为控制台编码时“参数不正确”

问题描述:

我得到以下错误:设置Unicode作为控制台编码时“参数不正确”

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) 

当我运行下面的代码行:

Console.OutputEncoding = Encoding.Unicode; 

任何想法,为什么?如果将编码设置为UTF8,则不会出现此错误。

Encoding.Unicode是UTF-16,它使用2个字节来编码所有字符。 ASCII字符(英文字符)在UTF-8(单字节,相同值)中是相同的,所以这可能是它工作的原因。

我的猜测是,Windows命令外壳不完全支持Unicode。有趣的是,Powershell 2 GUI确实支持UTF-16(据我所知),但是程序在那里抛出了相同的异常。

下面的代码工作这表明控制台对象可以有它的输出重定向和支持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 

我认为它与您使用的EncodingCodePage有关。具体见SetConsoleOutputCP Function。我不知道更多,对不起。

编辑:我报告了对SetConsoleOutputCP的引用,因为此函数在内部通过(设置操作)Console.OutputEncoding调用(通过PInvoke)。

Code Page Identifiers on MSDN列表时,UTF-16和UTF-32的编码进行管理-only:

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 

例如,他们不与下HKEY_LOCAL_MACHINE \ SYSTEM其他系统的代码页\ CURRENTCONTROLSET \控制\ NLS \代码页注册表中列出。