2017-06-14 38 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

相關問題