c# - 删除显示在图片框中的文件

标签 c# asp.net

我从 openfiledialoge 中选择文件并在图片框中显示它,在单击 delete 按钮时在文本框中显示它的名称 我遇到异常 进程无法访问该文件,因为它正在被使用由另一个进程。 我搜索了很多以解决此异常,但是当我尝试使用文本框中的图像名称关闭文件(即我在图片框中显示的文件)时,我没有很好地解决它们中的任何一个;使用 IsFileLocked 方法,这将关闭并删除特定目录路径的所有文件,但是我怎么能删除图片框中显示的唯一文件,我哪里出错了

     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;
        }
    }

在此先感谢您的帮助

最佳答案

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

The file remains locked until the Bitmap is disposed.

在您的代码中,您创建了位图并将其存储在局部变量中,但您永远不会在完成后处理它。这意味着您的图像对象已超出范围,但尚未释放对您尝试删除的图像文件的锁定。对于实现 IDisposable 的所有对象(如 Bitmap),您必须自行处理它们。参见 this question例如(或搜索其他 - 这是一个非常重要的概念!)。

要正确纠正问题,您只需在处理完图片后将其丢弃即可:

 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();
            }
        }

关于c# - 删除显示在图片框中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18009293/

相关文章:

asp.net - 如何通过 URL 访问 Azure SQL 数据库服务器管理 UI

c# - 从原始 HTML/CSS 内容从 ASP.NET 生成 PDF?

c# - 如何简化从 WinForms 到 WPF 的过渡

c# - 从 c# 处理到 MySql 的连接的最佳方法是什么

c# - 如何使用DataGridComboBoxColumn?

c# - 从插件加载 View 而不将其作为资源嵌入到 nopCommerce 中

c# - 无法在 C# WEB API REST 服务单元测试中模拟 Owin 上下文

asp.net - 如何在 ASP.NET 中导航页面

asp.net MVC如何仅修改一列

javascript - 将 jQuery 添加到母版页