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

时间:2009-01-07 07:59:39

标签: c# encoding

我收到以下错误:

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,我不会收到此错误。

3 个答案:

答案 0 :(得分:4)

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

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

以下代码可以显示Console对象可以重定向其输出并支持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

答案 1 :(得分:2)

根据Code Page Identifiers on MSDN列表,UTF-16和UTF-32编码仅限托管:

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 \ Control \ Nls \ CodePage下的其他系统代码页中列在注册表中。

答案 2 :(得分:0)

我认为这与你正在使用的CodePage的{​​{1}}有关。特别参见SetConsoleOutputCP Function。我不太了解,抱歉。

编辑:我报告了对Encoding的引用,因为此函数在内部通过({1}}的(设置操作)调用(通过PInvoke)。