【问题标题】:UWP BitmapEncoder close file?UWP BitmapEncoder 关闭文件?
【发布时间】:2016-11-28 16:51:35
【问题描述】:

如何在 UWP 上完成/关闭 BitmapEncoder?

InMemoryRandomAccessStream imras = new InMemoryRandomAccessStream();
await [...] //Fill stream
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imras);
[...] //Do something
StorageFile sf = await ApplicationData.Current.LocalFolder.CreateFileAsync("123.jpg", CreationCollisionOption.ReplaceExisting);
BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, await sf.OpenAsync(FileAccessMode.ReadWrite));
[...]
await bmpEncoder.FlushAsync();
imras.Dispose();

现在,当我尝试访问该文件时,我收到了 System.UnauthorizedAccessException,我必须关闭 UWP 应用才能访问此文件...如何关闭它?

【问题讨论】:

  • 如果您需要确定性销毁,请不要使用无法交付的语言 (C#) 或平台 (.NET)。 using 语句与 IDisposable 模式结合使用是行不通的。您可以实现一个 kludge(基于此),或完全删除不必要的托管层。

标签: c# io uwp uwp-xaml


【解决方案1】:

您需要处置每个 IDisposable 对象。最简单的方法是使用using 关键字。

using (var stream = await storageFile.OpenAsync()) // Or any other method that will open a stream.
{
   var bitmapDecoder = await BitmapDecoder.CreateAsync(stream);

   using (var randomAccessStream = new InMemoryRandomAccessStream())
   {
      var bitmapEncoder = await BitmapEncoder.CreateForTranscodingAsync(randomAccessStream, bitmapDecoder);

      // Do stuff.

      await bitmapEncoder.FlushAsync();

      var buffer = new byte[randomAccessStream.Size];

      await randomAccessStream.AsStream().ReadAsync(buffer, 0, buffer.Length);

      var someNewFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("SomeFileName", CreationCollisionOption.ReplaceExisting);

      await FileIO.WriteBytesAsync(someNewFile, buffer);
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2016-10-18
    • 2017-06-29
    • 2017-06-13
    • 2017-03-06
    相关资源
    最近更新 更多