Saving a stream containing an image to Local folder on Windows Phone 8

10,053

Your method SaveToLocalFolderAsync is working just fine. I tried it out on a Stream I passed in and it copied its complete contents as expected.

I guess it's a problem with the state of the stream that you are passing to the method. Maybe you just need to set its position to the beginning beforehand with file.Seek(0, SeekOrigin.Begin);. If that doesn't work, add that code to your question so we can help you.

Also, you could make your code much simpler. The following does exactly the same without the intermediate classes:

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);
    }
}
Share:
10,053
James Mundy
Author by

James Mundy

Updated on July 28, 2022

Comments

  • James Mundy
    James Mundy almost 2 years

    I'm currently trying to save an stream containing a jpeg image I got back from the camera to the local storage folder. The files are being created but unfortunately contain no data at all. Here is the code I'm trying to use:

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

    Any help saving files this way would be greatly appreciated - all help I have found online refer to saving text. I'm using the Windows.Storage namespace so it should work with Windows 8 too.

  • James Mundy
    James Mundy over 11 years
    You were correct, the stream position was at the end. School boy mistake. The code you've got above is a lot simpler so I'm going to use that instead. Thanks
  • Vitalii Vasylenko
    Vitalii Vasylenko over 10 years
    Damned, i downvoted it accidentally. Can you edit it a bit so i can re-vote?