Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi Experts,

My current project is a desktop application in c#.net. In this project I store images in "ImageFolder". Location is bin\debug or release\ImageFolder.

When I am storing or updating images in the folder they will properly save to that folder.

The code for saving images is:
C#
sAbpath = Application.StartupPath;
Image selImage = null;
selImage = Image.FromFile(sChoose_file).GetThumbnailImage(130, 160, ThumbnailCallback, new IntPtr());
selImage.Save(sAbpath + "\\ImageFolder\\" + strMemberPhotoName);
sNPath = "\\ImageFolder\\" + strMemberPhotoName;

This code runs properly.

But when updating new image for a particular id, the new image updates or saves propely, but the original image can not be delelet from the folder.

The code for that is:
C#
string sOldPath = sAbpath+sNPath;
//sNPath takes from the database 
if (File.Exists(sOldPath))
{
   File.Delete(sOldPath);
}

It will give this error:
"System.IO.IOException the process cannot access the file because it is being used by another process"

In case the application is run and I am opening the folder and try to delete the image, it doesn't allow to delete it and gives the same error, but after closing completely the application, the same image is deleted.

Please guide me weather it is the correct way.
its urgent..... [No, it's not]

Thanks and Regards
Chean Chopkar
Posted
Updated 13-Oct-10 4:23am
v2

Read the MSDN for Image.FromFile: http://msdn.microsoft.com/en-us/library/stf701f5.aspx[^]
Particularly read the bit where it says: "The file remains locked until the Image is disposed."

What this means is that when you load an Image from a file using Image.FromFile the original source file remains open and in use until the Image instance you created has be destroyed by the Garbage Collector. Since you have no control over this, you must Dispose of the Image manually when you have finished with it. If you don't and just let it go out of scope, then the file remains locked until the Garbage Collector needs the space. Could be tomorrow, could be next month. File is still locked until then.
 
Share this answer
 
Just Clone your Image and Dispose the original just after loading it:
C#
Image original = Image.FromFile(sChoose_file).GetThumbnailImage(/*...*/);
Image clone = (Image)original.Clone();
original.Dispose();
original = null;

// Now forget about original and never use it again.
// Work only with the clone.

clone.Save(/*...*/);
 
Share this answer
 

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