How do i remove a reference to a file (GDI Exception)

alander

Well-known member
Joined
Jun 26, 2007
Messages
120
Location
Singapore
Programming Experience
5-10
i have this code

VB.NET:
        Try
            picLogo.Image = Image.FromFile(Application.StartupPath & "\img\Logo.png")
        Catch
            If File.Exists(Application.StartupPath & "\img\Logo.png") = False Then

            End If

and when the user wanna change the logo i do this

VB.NET:
    Dim objOpenFileDialog As New OpenFileDialog

        'Set the Open dialog properties
        With objOpenFileDialog
            .Filter = "Image Files|*.jpg; *.jpeg; *.png; *.bmp; *.gif|Bitmap files (*.bmp)|*.bmp|JPEG files (*.jpg; *.jpeg)|*.jpg; *.jpeg|GIF files (*gif) |*.gif|PNG files(.png)| *.png"
            .FilterIndex = 1
            .Title = "Select organisation Logo..."
        End With

        If objOpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim selectedImage As Image
            Dim tmpPhoto As Bitmap
            Try
                selectedImage = Image.FromFile(objOpenFileDialog.FileName)
                tmpPhoto = New Bitmap(selectedImage, 350, 70)
                Dim g As Graphics = Graphics.FromImage(tmpPhoto)
                ' Select/change interpolation mode here.
                g.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
                g.DrawImage(selectedImage, 0, 0, 350, 70)
                Me.picLogo.Image = tmpPhoto
                tmpPhoto.Save(Application.StartupPath & "\img\logo.png", System.Drawing.Imaging.ImageFormat.Png)


            Catch exception As Exception
                MessageBox.Show(exception.message, "Exception Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
'' GDI Generic exception found

            End Try
        End If

        'Clean up
        objOpenFileDialog.Dispose()
        objOpenFileDialog = Nothing

But a GDI Error occurs, cos the picture already exist, i wanna let the user replace the existing picture

I did a work around and wanna do a file.delete and do a replacement, but it tells me my program is holding a reference to the file i loaded..

How can i stop that gdi exception or stop it from referencing?
 
Last edited:
Instead of Image.FromFile, open a IO.FileStream and use the Image.FromStream, this will not lock the file.
VB.NET:
Dim fs As New IO.FileStream("save.bmp", FileMode.Open, FileAccess.Read)
Picturebox1.Image = Image.FromStream(fs)
fs.Close()
 
Thank you v. much
 
Back
Top