dotnet/runtime

`ConsoleStream.ReadByte` throws when `Console.Encoding` is UTF-16

Open

#70.448 geöffnet am 8. Juni 2022

Auf GitHub ansehen
 (6 Kommentare) (1 Reaktion) (0 zugewiesene Personen)C# (5.445 Forks)batch import
area-System.Consolehelp wanted

Repository-Metriken

Stars
 (17.886 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 12T 11h) (661 gemergte PRs in 30 T)

Beschreibung

Description

An IOException is thrown when invoking Stream.ReadByte on a stream obtained from Console.OpenStandardInput after having set Console.Encoding to Encoding.Unicode.

Reproduction Steps

using System;
using System.Text;

namespace ConsoleApp1;

class Program
{
    static void Main()
    {
        Console.InputEncoding = Encoding.Unicode;
        var stdin = Console.OpenStandardInput();
        _ = stdin.ReadByte();
    }
}

The same exception is also thrown if you invoke Stream.Read with a buffer of length 1:

static void Main()
{
    Console.InputEncoding = Encoding.Unicode;
    var stdin = Console.OpenStandardInput();
    Span<byte> bytes = stackalloc byte[1];
    _ = stdin.Read(bytes);
}

Expected behavior

Stream.ReadByte returns the least significant byte of the read code unit (and the most significant byte of the same code unit on the next Stream.ReadByte invocation).

-or-

A more descriptive exception (NotSupportedException?) with a more meaningful message is thrown if this is an explicitly unuspported scenario.

Actual behavior

The following exception is thrown:

System.IO.IOException
  HResult=0x80070023
  Message=Unknown error (0x23)
  Source=System.Console
  StackTrace:
   at System.ConsolePal.WindowsConsoleStream.Read(Span`1 buffer)
   at System.IO.ConsoleStream.ReadByte()
   at ConsoleApp1.Program.Main() in C:\ConsoleApp1\Program.cs:line 12

Regression?

No response

Known Workarounds

Invoking Stream.Read with a buffer of length 2 or more. You can also use Encoding.CreateTranscodingStream with both the inner and outer encodings set to UTF-16 to wrap the input stream.

Configuration

.NET Core 6.0.300 / .NET Framework 4.8 Windows 10 x64

Other information

No response

Contributor Guide