Question Saving a file from MemoryStream

gchq

Well-known member
Joined
Dec 14, 2007
Messages
168
Programming Experience
10+
I have a function that downloads an image from a DB, saves it to a Temp directory and passes the string back to an app that opens it. Ran fine with .NET 2.0, but throws a variety of exceptions in .NET 4.0. (like System.AccessViolationException was unhandled). It somehow seems to relate to the saved file still being locked.

Any ideas?

Thanks

VB.NET:
Public Function ReturnLogoImage(ByVal HOAID As Integer) As String
        'Return the image from the DB and save to the Temp Dir - then pass that string back
        Dim strSQL As String = "SELECT Logo_Image, Logo_MIME FROM Annual"
        Dim vData2 As New DataConn
        vData2.HOA_ID = HOAID
        Dim vImage() As Byte = Nothing
        Dim vMIMEType As String = ""
        Try
            Using Reader As IDataReader = vData2.ExecuteReader(CommandType.Text, strSQL)
                While Reader.Read
                    vImage = Reader("Logo_Image")
                    vMIMEType = Reader("Logo_MIME")
                End While
            End Using
        Catch ex As Exception
            EmailError(ex.Message, "Functions 2138 " & strSQL)
            vData2 = Nothing
            Return "Error"
        End Try
        vData2 = Nothing
        'copy file to temp folder
        Dim vFileExtArray As Array = Split(vMIMEType, "/")
        Dim vFileExt As String = vFileExtArray(1)
        Dim vpath As String = PathString() & "Temp\Logo_" & RandomGenerator(8) & "." & vFileExt
        Dim vTempFile As New MemoryStream(vImage)
        Dim strSource As System.Drawing.Image = System.Drawing.Image.FromStream(vTempFile)
        If File.Exists(vpath) Then
            Try
                File.Delete(vpath)
            Catch ex As Exception
                EmailError(ex.Message, " 2248")
                Return "Error"
            End Try
        End If
        strSource.Save(vpath)
        strSource.Dispose()
        'vTempFile.Flush()
        'vTempFile.Close()

        'vTempFile.Dispose()
        Return vPath
    End Function
 

gchq

Well-known member
Joined
Dec 14, 2007
Messages
168
Programming Experience
10+
In the end managed to resolve it by copying the file and then sending the path of the copied file to the app. Not sure if this was the best approach, but it works...

strSource.Save(vpath)
If File.Exists(PathString() & "Temp\Logo_Temp." & vFileExt) Then
File.Delete(PathString() & "Temp\Logo_Temp." & vFileExt)
End If
File.Copy(vpath, PathString() & "Temp\Logo_Temp." & vFileExt)
vTempFile.Close()
strSource.Dispose()
Return PathString() & "Temp\Logo_Temp." & vFileExt
 
Top Bottom