fall try to change picturebox image c#

1. System.IO.File.Copy(fileName, Path.Combine(@"C:\images\", newFileName));

1 compile answer:

the process cannot access the file --- because it is being used by another process.

This file was using in pictureBox and I want to change pictureBox image and exchange the file to new one.

I found answers to use using like this:

using (pictureMain.Image = new Bitmap(newFileName))
{
    // Do some stuff
} 

but it doesn't work because i need the picture to be visible all time.. Any solutions and i will be happy. Thanks

Upvotes: 2

Views: 219

Answers (2)

Hossein Golshani
Hossein Golshani

Reputation: 1897

Try to load image, clone it and then release as follow.

using (Bitmap temp = new Bitmap(fileName))
    pictureMain.Image = new Bitmap(temp);

by this way file handle released and you can work with image that loaded into memory.

System.IO.File.Copy(fileName, Path.Combine(@"C:\images\", newFileName));

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81583

The problem is once the picture is loaded into the PictureBox it retains a Handle to the file. Hence why you cant copy it

To release the File Handle, you will need to Dispose() it.

// before copying the file make sure the file handle is released
// by calling dispose
if(PictureBox1.Image != null)
{
     PictureBox1.Image.Dispose();
     PictureBox1.Image = null;
} 

...

// It should be safe to copy the file now, as the handle should be released
File.Copy(fileName, Path.Combine(@"C:\images\",newFileName));

However, if you want to keep the image alive (Visually displayed) while trying to copy (which is what i think you are trying to do), you will essentially have to load the image, then clone it some how, then release the handle.

So i believe the following pattern should work for you when loading your image

// before loading any new image lets release any previously displayed imaged
if(PictureBox1.Image != null)
{
     PictureBox1.Image.Dispose();
     PictureBox1.Image = null;
} 

// this loads the image, copies it, then closes the handle
using (var bmpTemp = new Bitmap("image_file_path"))
{
    PictureBox1.Image = new Bitmap(bmpTemp);
}

...

// It should be safe to copy the file now, as the handle should be released
File.Copy(fileName, Path.Combine(@"C:\images\",     newFileName));

Final note: After you have finished with the image, make sure you dispose it. I.e if you create it, it needs to be disposed.

Upvotes: 2

Related Questions