Search code examples
.netvb.netfilestreamlocked-files

How to release filestream resource


I am saving an attachment from an email message. The attachment saves fine. My issue is that the filestream will not release the resource until the application exits. Neither Close or Dispose works. How is this done or is their a better way to save the data and have the file be unlocked.

Dim buffer As Byte() = fileAttachment.Content
strFileName = System.IO.Path.GetTempPath.Trim & "\" & fileAttachment.Name.Trim
Dim fileStream As New System.IO.FileStream(strFileName, IO.FileMode.Create)
fileStream.Write(buffer, 0, buffer.Length)

Solution

  • Wrap it in a Using:

    Using fileStream As New System.IO.FileStream(strFileName, IO.FileMode.Create)
        fileStream.Write(buffer, 0, buffer.Length)
    End Using
    

    Or more simply, just use File.WriteAllBytes.