tags:

views:

106

answers:

2

in my windows application there is a image saving process.i can save different images.the images details will seen in a grid ,when i click the corresponding row in grid the image will shown in a picturebox.i want to delete the open picture by pressing the delete key.i used the "deletefile(path)" code for this operation.but there is an error that "This file is used by another process."if anyone knows the solution for this problem please help me.thank you.

+1  A: 

Do you have a reference to a Bitmap object created from that file ? If so, the Bitmap object is locking the file and will prevent you from deleting it.

The problem is not where you delete your file, it lies in how you open your image to display it. Could you maybe add some code showing how you load your image ?

When you load an image using something list Bitmap.FromFile, the Bitmap object keeps a lock on the file until it is disposed. So you could simply use the

using(Bitmap bmp = Bitmap.FromFile(path))
{
  /* The code using the bitmap to display it goes here */
}

construct to force it to release the file once you do not need it. This will prevent it from locking. The reason it locks is that it does not load the whole bitmap in memory when you create the bitmap object, it loads it lazily on demand, so it needs to keep a lock on the file.

Locksfree
i can,t understand.please tell me in detail.please
i using this code to open the image to the picturebox " picturebox1.image=image.fromfile(specified path)
Then I guess you will have to keep a reference to the image you load as an attribute:img = Image.FromFile(path);picturebox1.Image = img;and then before deleting the image:picturebox1.Image = null;img.Dispose();img = null;/* Delete the file */
Locksfree
A: 

Open the imagefile using Image.FromStream and make sure you close the stream after the image is loaded. That way you sould have no locks on the file.

Added after comment.
I don't have Visual Studio at hand and I'm a c# guy but it should look something like this.

Dim stream As New FileStream(specified_path, FileMode.Open)
Dim image  As Image = Image.FromStream(stream)
picturebox1.image = image
stream.Close()
Nifle
my code is like thismy.computer.filesystem.deletefile(path)
i using this code to open the image to the picturebox"picturebox1.image=image.fromfile(specified path)how can i use the fromstream methode and how it will close
yes this working good.but the image which is displayed on the picturebox doen't clear