Reading text from IInputStream

Sam of Simple Samples 5,526 Reputation points
2023-12-05T02:25:12.11+00:00

I have an IInputStream Interface (Windows.Storage.Streams) object. It has text. That is all I know. I just want to read the text. I do not see how to determine the length of the text. It is not being read asynchronously therefore the length should be available.

I can create a buffer as in:

Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(200);

And read as in:

await linkstream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);

However I do not see how to use the buffer. I do not see how to get a byte array from the buffer or do anything to convert it to text.

I have looked at many samples. The Microsoft samples are samples of something else. They link to samples that are in a GitHub repository but the samples are huge, I just need a few lines that are relevant.

Universal Windows Platform (UWP)
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,631 questions
{count} vote

1 answer

Sort by: Most helpful
  1. Sam of Simple Samples 5,526 Reputation points
    2023-12-05T17:03:41.5233333+00:00

    If thestream is the stream with text then the following will get the text. Obviously a larger capacity can be specified for the buffer.

    StringBuilder sb = new StringBuilder();
    Windows.Storage.Streams.Buffer buffer = new(100);
    await thestream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);
    while (buffer.Length > 0)
    {
        using (var dataReader = DataReader.FromBuffer(buffer))
        {
            dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            sb.Append(dataReader.ReadString(buffer.Length));
            await thestream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);
        }
    }
    
    
    0 comments No comments