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

Epa*_*aga 6 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)
Run Code Online (Sandbox Code Playgroud)

当我运行以下代码行时:

 Console.OutputEncoding = Encoding.Unicode;
Run Code Online (Sandbox Code Playgroud)

知道为什么吗?如果我将编码设置为UTF8,我不会收到此错误.

use*_*789 4

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

我的猜测是 Windows Command Shell 不完全支持 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
Run Code Online (Sandbox Code Playgroud)