How to close the stream opened by StorageFile.OpenAsync?

帕菲菲 141 Reputation points
2020-04-18T14:30:04.783+00:00
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.

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. 帕菲菲 141 Reputation points
    2020-04-19T00:30:04.717+00:00
    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?

    0 comments No comments

0 additional answers

Sort by: Most helpful