question

Pafifi avatar image
0 Votes"
Pafifi asked ·

How to close the stream opened by StorageFile.OpenAsync?

 Dim b As StorageFile = Await a
 If b IsNot Nothing Then
  Dim d As BitmapEncoder = Await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Await b.OpenAsync(FileAccessMode.ReadWrite))
  d.SetSoftwareBitmap(c)
  Call d.FlushAsync()
 End If

This code runs normally for the first time. However, if the user chooses the same image file to save for the second time, meaning to replace it, the code fails because the previously opened stream was never closed. I didn't find any relevant methods to close the stream, or documents talking about it.

If the user closes the whole app, windows will forcibly close the stream. However, if the user makes another smaller image to save in the same file, then, after closing the whole app, the file still remains the previous larger size, and will never become smaller as the actual image data did.

windows-uwp
· 2
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I don't know much about VB.NET. Can you try to use using for this piece of code? so the resource will be disposed after using block.

0 Votes 0 ·

Tried. Now the stream may be closed, but the file size is still much larger than expected?

0 Votes 0 ·

1 Answer

Pafifi avatar image
0 Votes"
Pafifi answered ·
 Dim g As Stream = Await b.OpenStreamForWriteAsync
 g.SetLength(0)
 g.Close()
 Dim f As Streams.IRandomAccessStream = Await b.OpenAsync(FileAccessMode.ReadWrite), d As BitmapEncoder = Await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, f)
 d.SetSoftwareBitmap(c)
 Await d.FlushAsync()
 f.Dispose()

I solved this myself. Prior to the formal writing open a Stream and set its length to 0, and afterwards Dispose it. This seems somewhat weird however. Any better practices?

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.