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

柔情痞子 提交于 2019-12-11 05:22:09

问题


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).


回答1:


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);



回答2:


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!



来源:https://stackoverflow.com/questions/44549205/converting-a-streamreaderstring-to-be-compatible-with-uwp-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!