“参数不正确”将Unicode设置为控制台编码时 [英] "The parameter is incorrect" when setting Unicode as console 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,我不会收到此错误。
Any idea why? I do not get this error if I set the encoding to UTF8 instead.
推荐答案
Encoding.Unicode是UTF-16,它使用2字节来编码所有字符。 ASCII字符(英文字符)在UTF-8中是相同的(单字节,相同的值),所以这可能是它的工作原理。
Encoding.Unicode is UTF-16 which uses 2 bytes to encode all characters. The ASCII characters (English characters) are the same in UTF-8 (single bytes, same values), so that might be why it works.
我的猜测是Windows命令行管理程序不完全支持Unicode。有趣的是Powershell 2 GUI确实支持UTF-16(据我所知),但程序在那里抛出相同的异常。
My guess is that the Windows Command Shell doesn't fully support Unicode. Funny that the Powershell 2 GUI does support UTF-16 (as far as I know), but the program throws the same exception there.
以下代码可以显示Console对象可以重定向其输出,并支持Encoding.Unicode:
The following code works which shows that the Console object can have its output redirected 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
这篇关于“参数不正确”将Unicode设置为控制台编码时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!