pythonimus
pythonimus

Reputation: 293

UWP BitmapEncoder close file?

How can I finalize/close the BitmapEncoder on UWP?

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

Now when I try to access the file, I get a System.UnauthorizedAccessException, I have to close the UWP app to be able to access this file... How can I close it?

Upvotes: 1

Views: 561

Answers (1)

khamitimur
khamitimur

Reputation: 1088

You need to dispose every IDisposable object. The easiest way is to use using keyword.

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

Upvotes: 1

Related Questions