问题
I have picturebox and i trying write code when the users loads another image on picturebox the old file which was in picture to be deleted. I trying to find solution for for 24 hrs still i didn't able find fully working solution.
I came up with 1 partial solution and following is partial code
profilePictureBox.Dispose(); // When I use This After The Function Executed
PictureBox Disappears But File Delete Successfully.
try
{
if (File.Exists(oldfilename))
{
File.Delete(oldfilename);
profilePicPictureBox.Load(picPath);
}
else
{
MessageBox.Show("File Not Found");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
"old filename" will contain previous filename to delete and "picPath" will contains new path of image user chosen.
and also when tried method like
profilePictureBox.Image = null;
i am getting below error
System.IO.IOExecption:The Process cannot access the file
'filepath' because it is being used by another process.
回答1:
You need to load the image into memory and add it to the picture box without loading it directly from a file. the Load
function keeps the file open and you won't be able to delete it. Try this instead. NOTE: there is no error checking in this code.
using (FileStream fs = new FileStream("c:\\path\\to\\image.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
using (MemoryStream ms = new MemoryStream(buffer))
this.pictureBox1.Image = Image.FromStream(ms);
}
File.Delete("c:\\path\\to\\image.jpg");
This will open the file and read its contents into a buffer then close it. It will load the picture box with the memory stream full of "copied" bytes, allowing you to freely delete the image file it was loaded from.
来源:https://stackoverflow.com/questions/25101377/delete-file-which-was-in-picture-box-before-loading-another-picture