错误:“进程无法访问..因为它正被另一个进程使用.“中的”删除图像”
本文关键字:进程 另一个 删除 图像 中的 访问 错误 因为 | 更新日期: 2023-09-27 18:27:40
我知道其他人也有类似的问题,但我的问题特定于图像...我有一个图像功能,如下所示:
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;
}
为了加载图像,我有这个功能:
static public void loadimage(PictureBox pictureBox, string img, string nameform, string folderform)
{
try
{
if (img != "Null_0_Null")
if (!System.IO.File.Exists(Application.StartupPath + @"'userpictures'" + nameform + @"'" + folderform + @"'" + img))
{
pictureBox.BackgroundImage = Image.FromFile(Application.StartupPath + "''filepictures''default4.PNG");
}
else
{
pictureBox.BackgroundImage =Image.FromFile(Application.StartupPath + @"'userpictures'" + nameform + @"'" + folderform + @"'" + img);
}
}
catch { }
}
在我的表单中,我调用此函数。对于设置图像,我在我的表单中编写一个私有字符串:
string img1;
为了在我的表单加载中加载图像,请写下以下内容:
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
一次并在Setimage
中重用对象(你在单个if
条件下加载它两次...... - 完成后处理掉所有
Image
- 在设置新
BackgroundImage
之前处理旧
只要在删除文件之前处理掉与文件相关的所有Image
,就应该没问题。