2017-06-14 40 views
0

我遇到了使用StreamReader类的障碍。在StreamReader Class文档页面上,它指出 支持版本信息标题“Universal Windows Platform - Available since 8”下的通用Windows平台(UWP)。将StreamReader(字符串)转换为与UWP API兼容?

进一步检查其构造函数后,StreamReader(Stream)构造函数确实支持UWP应用程序,但StreamReader(String)构造函数不支持它们。

目前我使用的是完整的文件路径的StreamReader(String)构造要被读取,

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

我正在寻找了解如何我的代码转换为一个StreamReader(字符串)一个StreamReader(流)。

+0

是[this](https://stackoverflow.com/questions/1879395/how-to-generate-a-stream-from-a-string)你想完成什么? – Kilazur

+0

你是字符串文件名还是字符串。要读取字符串,请使用StringReader(string)。 StreamReader中的字符串是一个文件名。 – jdweng

+0

@Kilazur,在某种意义上是的。我想使用路径。 – jtth

回答

0

在UWP StreamReader只接受Stream与其他选项。不是字符串。

所以使用StreamReader从一个特定的路径,你需要得到StorageFile

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

端起来解决我自己的问题!该文档是现货。

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

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

古朴典雅。再次感谢所有参与者!

+0

如果路径位于应用程序文件夹之外,您将收到ACCESS_DENIED错误。 –

+1

欢迎使用[sandboxed](https://docs.microsoft.com/en-us/windows/uwp/files/file-access-permissions)环境!您需要获取[StorageFile]实例(https://docs.microsoft.com/en-us/uwp/api/windows.storage.storagefile),通常通过[FileOpenPicker](https://docs.microsoft .com/en-us/uwp/api/windows.storage.pickers.fileopenpicker),然后在AVK的答案中使用该方法。您无法直接使用路径访问文件。 –

+0

@MehrzadChehraz我相信这正是我正在发生的事情......有没有解决方法或已知的解决方案?我需要能够访问构建应用程序文件夹之外的文件,因为它是一个适用于任何用户的动态程序。会有[FileStreams params](https://msdn.microsoft.com/en-us/library/system.io.filestream(v = vs.110).aspx)在这里工作吗? – jtth

相关问题