user626528
user626528

Reputation: 14419

How do I read exactly one char from a Stream?

I have a Stream with some text data (can be ASCII, UTF-8, Unicode; encoding is known). I need to read exactly one char from the stream, without advancing stream position any longer. StreamReader is inappropriate, as it aggressively prefetches data from the stream.
Ideas?

Upvotes: 1

Views: 1332

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

If you want to read and decode the text one byte at a time, the most convenient approach I know of is to use the System.Text.Decoder class.

Here's a simple example:

class Program
{
    static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.Unicode;

        string originalText = "Hello world! ブ䥺ぎょズィ穃 槞こ廤樊稧 ひゃご禺 壪";
        byte[] rgb = Encoding.UTF8.GetBytes(originalText);
        MemoryStream dataStream = new MemoryStream(rgb);
        string result = DecodeOneByteAtATimeFromStream(dataStream);

        Console.WriteLine("Result string: \"" + result + "\"");
        if (originalText == result)
        {
            Console.WriteLine("Original and result strings are equal");
        }
    }

    static string DecodeOneByteAtATimeFromStream(MemoryStream dataStream)
    {
        Decoder decoder = Encoding.UTF8.GetDecoder();
        StringBuilder sb = new StringBuilder();
        int inputByteCount;
        byte[] inputBuffer = new byte[1];

        while ((inputByteCount = dataStream.Read(inputBuffer, 0, 1)) > 0)
        {
            int charCount = decoder.GetCharCount(inputBuffer, 0, 1);
            char[] rgch = new char[charCount];

            decoder.GetChars(inputBuffer, 0, 1, rgch, 0);
            sb.Append(rgch);
        }
        return sb.ToString();
    }
}

Presumably you are already aware of the drawbacks of processing data of any sort just one byte at a time. :) Suffice to say, this is not a very efficient way to do things.

Upvotes: 2

Related Questions