12

這是從資源文件獲取的正確方法嗎?從資源文件/內容獲取流

Uri uri = new Uri(fullPath); 

    StorageFile storageFile = 
     await Windows.Storage.StorageFile. 
     GetFileFromApplicationUriAsync(uri); 

    IRandomAccessStreamWithContentType randomAccessStream = 
     await storageFile.OpenReadAsync(); 

    IInputStream resourceStream = (IInputStream) 
     randomAccessStream.GetInputStreamAt(0); 

我所有的其他來源(HTTP和本地存儲)返回一個Stream對象,而且它是痛苦的必須使用一個或另一個的if-else代碼。

我也嘗試過創建一個MemoryStream出來,但我甚至找不到一個方法來獲取字節......請幫助。

uint size = (uint)randomAccessStream.Size; 
    IBuffer buffer = new Windows.Storage.Streams.Buffer(size); 
    await randomAccessStream.ReadAsync(buffer, size, 
     InputStreamOptions.None); 

    Stream stream = new MemoryStream(buffer); // error takes byte[] not IBuffer 

IInputStream.ReadAsync從資源讀取時(): http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.streams.iinputstream.readasync.aspx

而Stream.Read()和Stream.ReadAsync()是這樣的:

http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx

http://msdn.microsoft.com/en-us/library/hh137813.aspx

謝謝

回答

23

好的,我發現它!

StorageFile storageFile = 
     await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri); 

    var randomAccessStream = await storageFile.OpenReadAsync(); 
    Stream stream = randomAccessStream.AsStreamForRead(); 
+0

可能流轉換爲StorageFile? :○ – jdnichollsc

7

你也可以做到在一個較小的線:

Stream stream = await storageFile.OpenStreamForReadAsync();