How do I read exactly one char from a Stream?

前端 未结 1 942
挽巷
挽巷 2021-01-23 07:48

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 lon

相关标签:
1条回答
  • 2021-01-23 08:43

    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.

    0 讨论(0)
提交回复
热议问题