将包含图像的流保存到Windows Phone 8上的本地文件夹

Jam*_*ndy 8 c# windows-phone windows-runtime windows-phone-8

我目前正在尝试保存包含我从相机返回到本地存储文件夹的jpeg图像的流.正在创建文件,但遗憾的是根本不包含任何数据.这是我正在尝试使用的代码:

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();
    }
  } 
}
Run Code Online (Sandbox Code Playgroud)

任何以这种方式保存文件的帮助都将非常感激 - 我在网上找到的所有帮助都是指保存文本.我正在使用Windows.Storage命名空间,因此它也适用于Windows 8.

Dam*_*Arh 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);
    }
}
Run Code Online (Sandbox Code Playgroud)