Saving a stream containing an image to Local folde

2019-03-08 22:29发布

问题:

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.

回答1:

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