2013-02-01 110 views
9

我正在嘗試保存包含從相機返回到本地存儲文件夾的jpeg圖像的流。文件正在創建,但不幸的是根本沒有數據。下面是我嘗試使用代碼:將包含圖像的流保存到Windows Phone上的本地文件夾8

public async Task SaveToLocalFolderAsync(Stream file, string fileName) 
{ 
    StorageFolder localFolder = ApplicationData.Current.LocalFolder; 
    StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); 

    using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) 
    { 
    using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0)) 
    { 
     using (DataWriter dataWriter = new DataWriter(outputStream)) 
     { 
     dataWriter.WriteBytes(UsefulOperations.StreamToBytes(file)); 
     await dataWriter.StoreAsync(); 
     dataWriter.DetachStream(); 
     } 
     await outputStream.FlushAsync(); 
    } 
    } 
} 

public static class UsefulOperations 
{ 
    public static byte[] StreamToBytes(Stream input) 
    { 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     input.CopyTo(ms); 
     return ms.ToArray(); 
    } 
    } 
} 

的任何文件保存這樣的幫助,將不勝感激 - 所有幫助我發現網上參考保存文本。我正在使用Windows.Storage命名空間,因此它也可以在Windows 8上運行。

+0

您確定這是Windows PHONE 8嗎?你沒有使用'IsolatedStorageFile.GetUserStoreForApplication()' –

+1

絕對可以,你現在可以使用上面的命名空間,代碼也可以在Windows 8上運行。 –

+0

每天學點新東西:) –

回答

26

你的方法SaveToLocalFolderAsync工作得很好。我試過了,我通過了Stream,並按預期複製了其完整內容。

我想這是您傳遞給方法的流的狀態問題。也許你只需要預先用file.Seek(0, SeekOrigin.Begin);來設置它的位置。如果這不起作用,請將該代碼添加到您的問題中,以便我們可以爲您提供幫助。

此外,你可以讓你的代碼更簡單。如果沒有中間級別,以下內容完全相同:

public async Task SaveToLocalFolderAsync(Stream file, string fileName) 
{ 
    StorageFolder localFolder = ApplicationData.Current.LocalFolder; 
    StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); 
    using (Stream outputStream = await storageFile.OpenStreamForWriteAsync()) 
    { 
     await file.CopyToAsync(outputStream); 
    } 
} 
+0

謝謝,那可能是對的,今天我會看看。 –

+0

你是對的,流的位置在最後。學校男孩的錯誤。你上面的代碼要簡單得多,所以我要用它來代替。謝謝 –

+0

該死的,我意外地低估了它。你可以編輯一下,這樣我可以重新投票嗎? –

相關問題