删除图片框中显示的文件

我正在从openfiledialoge中选择文件并将其显示在picturebox中,当我点击delete按钮时,它在文本框中显示我正在获取exceptionThe process cannot access the file because it is being used by another process. 我搜索了很多这个例外以获得解决,但是当我尝试使用imagename关闭文件时,我尝试关闭文件,即我在图片框中显示的文件; 使用IsFileLocked方法,这会关闭并删除特定目录路径的所有文件,但是如何删除picturebox中显示的唯一文件,我错了

  public partial class RemoveAds : Form { OpenFileDialog ofd = null; string path = @"C:\Users\Monika\Documents\Visual Studio 2010\Projects\OnlineExam\OnlineExam\Image\"; // this is the path that you are checking. public RemoveAds() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (System.IO.Directory.Exists(path)) { ofd = new OpenFileDialog(); ofd.InitialDirectory = path; DialogResult dr = new DialogResult(); if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Image img = new Bitmap(ofd.FileName); string imgName = ofd.SafeFileName; txtImageName.Text = imgName; pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr()); ofd.RestoreDirectory = true; } } else { return; } } private void button2_Click(object sender, EventArgs e) { //Image img = new Bitmap(ofd.FileName); string imgName = ofd.SafeFileName; if (Directory.Exists(path)) { var directory = new DirectoryInfo(path); foreach (FileInfo file in directory.GetFiles()) { if(!IsFileLocked(file)) file.Delete(); } } } public static Boolean IsFileLocked(FileInfo path) { FileStream stream = null; try { //Don't change FileAccess to ReadWrite, //because if a file is in readOnly, it fails. stream = path.Open ( FileMode.Open, FileAccess.Read, FileShare.None ); } catch (IOException) { //the file is unavailable because it is: //still being written to or being processed by another thread //or does not exist (has already been processed) return true; } finally { if (stream != null) stream.Close(); } //file is not locked return false; } } 

在此先感谢您的帮助

(先前)接受的这个问题的答案是非常糟糕的做法。 如果您阅读 System.Drawing.Bitmap上的文档 ,特别是对于从文件创建位图的重载,您会发现:

文件保持锁定状态,直到处理了位图。

在您的代码中,您创建位图并将其存储在本地变量中,但是在完成后您永远不会丢弃它。 这意味着您的图像对象已超出范围但尚未释放其对您尝试删除的图像文件的锁定。 对于所有实现IDisposable对象(如Bitmap ),您必须自己处理它们。 例如,请查看此问题 (或搜索其他人 – 这是一个非常重要的概念!)。

要正确纠正问题,您只需在完成后处理图像:

  if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Image img = new Bitmap(ofd.FileName); // create the bitmap string imgName = ofd.SafeFileName; txtImageName.Text = imgName; pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr()); ofd.RestoreDirectory = true; img.Dispose(); // dispose the bitmap object } 

请不要接受以下答案中的建议 – 你几乎不需要打电话给GC.Collect ,如果你需要这样做以使事情有效,那么这应该是一个非常强烈的信号,表明你正在做其他错误的事情。

此外,如果您只想删除一个文件(您显示的位图),您的删除代码是错误的,并且将删除目录中的每个文件(这只是重复Adel的观点)。 此外,我不建议只保存一个全局OpenFileDialog对象来存储文件名,而是建议摆脱它并保存文件信息:

 FileInfo imageFileinfo; //add this //OpenFileDialog ofd = null; Get rid of this private void button1_Click(object sender, EventArgs e) { if (System.IO.Directory.Exists(path)) { OpenFileDialog ofd = new OpenFileDialog(); //make ofd local ofd.InitialDirectory = path; DialogResult dr = new DialogResult(); if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Image img = new Bitmap(ofd.FileName); imageFileinfo = new FileInfo(ofd.FileName); // save the file name string imgName = ofd.SafeFileName; txtImageName.Text = imgName; pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr()); ofd.RestoreDirectory = true; img.Dispose(); } ofd.Dispose(); //don't forget to dispose it! } else { return; } } 

然后在第二个按钮处理程序中,您可以删除您感兴趣的文件。

  private void button2_Click(object sender, EventArgs e) { if (!IsFileLocked(imageFileinfo)) { imageFileinfo.Delete(); } } 

使用此代码

 string imgName = ofd.SafeFileName; if (Directory.Exists(path)) { var directory = new DirectoryInfo(path); foreach (FileInfo file in directory.GetFiles()) { GC.Collect(); GC.WaitForPendingFinalizers(); file.Delete(); } } 

您的button2_Click事件处理程序循环遍历目录中的所有文件并执行删除操作。

您需要更改以下代码:

  public partial class RemoveAds : Form { OpenFileDialog ofd = null; string path = @"C:\Users\Monika\Documents\Visual Studio 2010\Projects\OnlineExam\OnlineExam\Image\"; // this is the path that you are checking. string fullFilePath; public RemoveAds() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (System.IO.Directory.Exists(path)) { ofd = new OpenFileDialog(); ofd.InitialDirectory = path; DialogResult dr = new DialogResult(); if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Image img = new Bitmap(ofd.FileName); string imgName = ofd.SafeFileName; txtImageName.Text = imgName; pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr()); fullFilePath = ofd.FilePath; ofd.RestoreDirectory = true; } } else { return; } } private void button2_Click(object sender, EventArgs e) { FileInfo file = new FileInfo(fullFilePath); if(!IsFileLocked(file)) file.Delete(); } } public static Boolean IsFileLocked(FileInfo path) { FileStream stream = null; try { //Don't change FileAccess to ReadWrite, //because if a file is in readOnly, it fails. stream = path.Open ( FileMode.Open, FileAccess.Read, FileShare.None ); } catch (IOException) { //the file is unavailable because it is: //still being written to or being processed by another thread //or does not exist (has already been processed) return true; } finally { if (stream != null) stream.Close(); } //file is not locked return false; } } 

通过使用GetThumnailImage,您必须指定静态的宽度和高度。 请改用Load方法。 例如:pictureBox1.Load(图像的路径); 通过使用此function,在关闭应用程序之前删除图像或文件夹没有任何问题。 不需要创建其他方法。 希望这可以帮助

我遇到了同样的问题:我在PictureBox中加载了一个文件,当我尝试删除它时,我得到了同样的exception。
仅在显示图像时才会发生这种情况。
我尝试了所有这些:

 picSelectedPicture.Image.Dispose(); picSelectedPicture.Image = null; picSelectedPicture.ImageLocation = null; 

并且仍然有相同的例外。
然后我在CodeProject上找到了这个: [c#]删除在picturebox中打开的图像 。
它不是使用PictureBox.Load()而是从文件创建一个Image并将其设置为PictureBox.Image

 ... // Create image from file and display it in the PictureBox Image image = GetCopyImage(imagePath); picSelectedPicture.Image = image; ... private Image GetCopyImage(string path) { using (Image image = Image.FromFile(path)) { Bitmap bitmap = new Bitmap(image); return bitmap; } } 

删除文件时不再有例外。
恕我直言,这是最合适的解决方案。

编辑
我忘了提到你可以在显示后立即安全删除文件:

 ... // Create image from file and display it in the PictureBox Image image = GetCopyImage(imagePath); picSelectedPicture.Image = image; System.IO.File.Delete(imagePath); ...