jtth
jtth

Reputation: 886

Converting a StreamReader(String) to be compatible with UWP API?

I'm running into a snag utilizing the StreamReader class. On the StreamReader Class documentation page, it states that it supports Universal Windows Platforms (UWPs) under the Version Information header, "Universal Windows Platform - Available since 8".

Upon further inspection of its constructors, the StreamReader(Stream) constructors do support UWP apps, however the StreamReader(String) constructors do not support them.

I'm currently using the StreamReader(String) constructor with the complete file path to to be read,

using (StreamReader sr = new StreamReader(path))
{
    ...
}

I'm seeking to learn how to convert my code for a StreamReader(String) to a StreamReader(Stream).

Upvotes: 2

Views: 632

Answers (2)

jtth
jtth

Reputation: 886

Ended up solving my own problem! The documentation is spot on.

From

using (StreamReader sr = new StreamReader(path))
{
    ...
}

To

using (FileStream fs = new FileStream(path, FileMode.Open))
{
   using (StreamReader sr = new StreamReader(fs))
   {
      ...
   }
}

Simple and elegant. Thanks again to all who contributed!

Upvotes: 0

AVK
AVK

Reputation: 3923

In UWP StreamReader accepts only Stream with additional Options. Not String.

So to use StreamReader from a particular path, you need to get the StorageFile

StorageFile file = await StorageFile.GetFileFromPathAsync(<Your path>);
var randomAccessStream = await file.OpenReadAsync();
Stream stream = randomAccessStream.AsStreamForRead();
StreamReader str = new StreamReader(stream);

Upvotes: 2

Related Questions