Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I'm doing this at the start of my VB program to place a logo on a panel:

pnLogo.BackgroundImage = Image.FromFile(ProgramDataPath & "\logo.jpg")

But the user should also be able to pick another image to be the logo at anytime. Once he does that, the program deletes the old logo.jpg at its ProgramDataPath and copy the new image to its place.

However, when I try to delete the current logo.jpg, I get an exception saying that the file is open by a process and cannot be deleted.

Anyone knows how to close that file so that it can be deleted?
Thanks in advance

What I have tried:

I tried setting pnLogo.BackgroundImage = Nothing, tried disposing the panel pnLogo, tried setting a variable to the image instead (Public LogoImage As System.Drawing.Image = Image.FromFile(ProgramDataPath & "\logo.jpg"))... but nothing works.
Posted
Updated 27-Feb-18 7:58am

1 solution

The usual solution given is to make a (memory) copy of the image before using it with a picturebox, e.g.
VB
Dim bmp as Bitmap = Nothing
Using img as Image = Image.FromFile(fileName)
    bmp = new Bitmap(img)
End Using
pnLogo.BackgroundImage = bmp

But, if you want to keep the code you already have, just dispose the image in the picturebox to unlock the file:
VB
pnLogo.BackgroundImage.Dispose()
pnLogo.BackgroundImage = Nothing
 
Share this answer
 
Comments
Richard Deeming 27-Feb-18 14:11pm    
NB: Both the Bitmap constructor[^] and the Image.FromStream method[^] have a warning in the remarks:
"You must keep the stream open for the lifetime of the Bitmap."

Also, calling pnLogo.BackgroundImage.Dispose won't release the low-level lock that GDI+ puts on the file.
[no name] 27-Feb-18 14:19pm    
I've tested both my examples, and they both worked as expected: the file was released (with Dispose()) and deleted (with File.Delete()). Is this not working for you?
Tesouro 27-Feb-18 18:12pm    
Thanks Peter, the 1st code you posted worked perfectly! The second one did not work here. File.Delete() will still give a "file is open" exception if I do a pnLogo.BackgroundImage.Dispose() and pnLogo.BackgroundImage=Nothing before it.
[no name] 27-Feb-18 18:23pm    
You're welcome, and thanks for your reply and vote. Strange that the second code works well in my test application and not in your app. I'll have another look at it... - also thanks Richard.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900