图片管理项目中File.Delete触发System.IO.IOException问题求助
解决图片删除时的System.IO.IOException问题
问题根源
Image.FromFile()方法会锁定图片文件,直到对应的Image对象被完全释放。你的UI控件(PictureBox)持有这些Image对象的引用,导致删除时文件仍被当前进程占用,触发异常。
具体解决方案
改用流加载图片,解除文件锁定
替换所有Image.FromFile()的调用,使用FileStream读取文件并创建Image对象,读取完成后关闭流,避免锁定原文件:// 修改UpdateInterfacePictures中的图片加载逻辑 using (FileStream fs = new FileStream(Database.Pictures[index].Path_, FileMode.Open, FileAccess.Read)) { picture.BackgroundImage = Image.FromStream(fs); } // 修改UpdateInterface中的图片加载逻辑 using (FileStream fs = new FileStream(Database.Pictures[PictureIndex].Path_, FileMode.Open, FileAccess.Read)) { pictureBox_Picture.BackgroundImage = Image.FromStream(fs); }删除前主动释放UI中的图片资源
在执行删除操作前,清空并释放对应PictureBox的BackgroundImage,避免残留引用占用文件:public void button_Delete_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Are you sure you want to delete " + Database.Pictures[PictureIndex].Name, "Moments Remember", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { // 释放当前主显示框的图片资源 if (pictureBox_Picture.BackgroundImage != null) { pictureBox_Picture.BackgroundImage.Dispose(); pictureBox_Picture.BackgroundImage = null; } // 释放列表中所有显示的图片资源(可根据索引精准释放,这里简化处理) PictureBox[] pictureBoxes = { pictureBox_Picture_1, pictureBox_Picture_2, pictureBox_Picture_3, pictureBox_Picture_4, pictureBox_Picture_5, pictureBox_Picture_6, pictureBox_Picture_7, pictureBox_Picture_8, pictureBox_Picture_9, pictureBox_Picture_10 }; foreach (var picBox in pictureBoxes) { if (picBox.BackgroundImage != null) { picBox.BackgroundImage.Dispose(); picBox.BackgroundImage = null; } } Database.Pictures.Remove(Database.Pictures[PictureIndex]); Close(); } }修复文件存在性判断逻辑
当前Pictures.Contains(new Picture(PicturesPath[i]))无法正确判断文件是否在列表中(引用比较而非路径比较),替换为路径直接对比:public void DeleteRemovedPictures() { string[] PicturesPath = Directory.GetFiles("../Pictures/"); foreach (string path in PicturesPath) { bool isInDatabase = Database.Pictures.Any(p => p.Path_ == path); if (!isInDatabase) { File.Delete(path); } } }
内容的提问来源于stack exchange,提问作者Twentyium
相关产品推荐
相关产品推荐

