C# 错误:“进程无法访问…因为它正被另一个进程使用。”在删除映像中
我知道其他人也有类似的问题,但我的问题是针对图像的。。。 我有如下图像功能:C# 错误:“进程无法访问…因为它正被另一个进程使用。”在删除映像中,c#,error-handling,C#,Error Handling,我知道其他人也有类似的问题,但我的问题是针对图像的。。。 我有如下图像功能: static public string Setimage(PictureBox pictureBox, OpenFileDialog ofd,string nameform,string folderform) { ofd.Title = "Select Pictures"; ofd.Filter = "Pictures(*.jpg, *.jpeg, *.jpe
static public string Setimage(PictureBox pictureBox, OpenFileDialog ofd,string nameform,string folderform)
{
ofd.Title = "Select Pictures";
ofd.Filter = "Pictures(*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png | All file (*.*)| *.*";
ofd.DefaultExt = ".jpg"; // Default file extension
string namefile = "";
// Process open file dialog box results
if (ofd.ShowDialog() == DialogResult.OK)
{
// try
//{
string fileName = ofd.FileName;
if (ofd.SafeFileName.Length <= 50)
if (Image.FromFile(fileName).Width >= 640 && Image.FromFile(fileName).Height >= 480)
{
namefile = ofd.SafeFileName;
if (namefile != "Null_0_Null" || namefile != null)
{
string oldPath = @ofd.FileName;
string newFileName = namefile;
newpath = Application.StartupPath + @"\userpictures\" + @"Apartment\";
deladdress = newpath + folderform + @"\" + @newFileName;
Random rand = new Random();
string pp=newpath+folderform;
// string pdest;
#region Check Directory And File To copy
if (Directory.Exists(newpath + folderform))
{
if (!File.Exists(newpath + folderform + @"\" + @newFileName))
File.Copy(oldPath, newpath + folderform + @"\" + @newFileName);
// else
// {
// File.Delete(newpath + folderform + @"\" + @newFileName);
// File.Copy(oldPath, newpath + folderform + @"\" + @newFileName);
//}
}
else
{
Directory.CreateDirectory(newpath + folderform);
File.Copy(oldPath, newpath + folderform + @"\" + @newFileName);
}
#endregion
pictureBox.BackgroundImage = Image.FromFile(newpath + folderform + @"\" + @newFileName);
}
else { MessageBox.Show("filename" + namefile + "Not valid"); }
}
else { MessageBox.Show("Size of file not valid"); }
else { MessageBox.Show("size of name file not valid"); }
// }
// catch { MessageBox.Show("your file that you selected is not valid please select anyone."); }
}
return namefile;
}
在我的形式中,我称之为函数。对于set image,我在表单中写入一个私有字符串:
string img1;
要在我的表单load中加载图像,请编写以下内容:
loadimage(pictureBox1, "Blue hills.jpg","me", "Apartment");
img1 = "Blue hills.jpg";
对于Setimage,我有以下内容:
img1=Setimage(pictureBox1, openFileDialog1,"me", "Apartment");
而当我使用此代码删除图像时显示我的错误进程无法访问
System.IO.File.Delete("image path");
使用Image.FromFile时,将打开该文件的文件句柄,并将其保持打开状态,直到图像被释放
你应该:
只调用Image.FromFile一次,并在一个if条件下重复使用Setimage中的对象加载两次。。。
处理完所有图像后,请将其处理掉
在设置新背景图像之前,请先处理旧背景图像
只要在删除文件之前处理掉与该文件相关的所有图像,就不会有问题。我希望catch{}不在您真正的代码中。。。而且它的缩进更容易理解,理想情况下还有更多的约定方法名。。。是一次性的,并在原始图像文件上保留锁,但是您正在使用那些FromFile方法泄漏它们,这些方法甚至没有分配给局部变量。您没有在某处关闭文件句柄。使用using块,您就不必再担心这个问题了。
System.IO.File.Delete("image path");