我使用该程序后删除文件夹

时间:2013-02-08 15:39:22

标签: c#

我创建了一个对话框程序,当我为一个文件夹的任何图片创建一个图片框时,当我关闭此对话框时,我想删除图片框,但是,我发现了一个例外,这个例外告诉我:文件0.jpg由另一个进程使用

但是,所以,我试图处理所有的图片框......我已经尝试了所有可能的东西,据我所知,当然......

所以,我的示例代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace delFolder
{
    public partial class FormPictureView : Form
    {
        private PictureBox pbSel = null;

        public FormPictureView()
        {
            InitializeComponent();

            AddPictureBox();
        }

        private void AddPictureBox()
        {
            int linha = 0;
            int x = 10, y = 10;
            string pngOutputPath = @"images\";

            string[] files = Directory.GetFiles(pngOutputPath);
            for (int i = 0; i < files.Length; i++)
            {
                if (linha == 2)
                {
                    x = 10;
                    y += 360;
                    linha = 0;
                }
                PictureBox pb = new PictureBox();
                pb.Name = string.Format("pb{0}", i);
                pb.Size = new Size(236, 321);
                pb.SizeMode = PictureBoxSizeMode.Zoom;
                pb.Image = Image.FromFile(string.Format("{0}{1}.jpg", pngOutputPath, i));
                pb.BackColor = Color.White;
                pb.Click += new EventHandler(pb_Click);
                pb.Tag = string.Format("{0}{1}.jpg", pngOutputPath, i);
                pb.Location = new System.Drawing.Point(x, y);
                panel1.Controls.Add(pb);
                x += 280;
                linha++;
            }
        }

        private void pb_Click(object sender, EventArgs e)
        {
            if (pbSel != null)
                pbSel.BorderStyle = BorderStyle.None;
            PictureBox pb = (PictureBox)sender;
            pb.BorderStyle = BorderStyle.FixedSingle;
            pbSel = pb;
            MessageBox.Show(pb.Tag.ToString());
        }
    }
}

并且,此对话框是主窗体的MDIParent ...,当我关闭此对话框时,我尝试删除图片框,但是,这是不可能的:( 我怎么解决这个问题?

3 个答案:

答案 0 :(得分:4)

您需要Dispose() PictureBox中的Image

答案 1 :(得分:1)

如果设置ImageLocation属性而不是Image属性,则不会获取文件上的锁定,您将能够删除该文件。但是,PictureBox将无法再使用该图像,并且将显示“无图像”图标。

要解决此问题,您可以在删除之前将图像复制到内存中:

string imgPath = string.Format("{0}{1}.jpg", pngOutputPath, i);
// Retrieve image from file
Image img = Image.FromFile(imgPath);
// Create new canvas to paint the picture in
Bitmap tempImg = new Bitmap(img.Width, img.Height);
// Paint image in memory
using (Graphics g = Graphics.FromImage(tempImg))
{
   g.DrawImage(img, 0, 0);
}
// Assign image to PictureBox
pb.Image = tempImg;
// Dispose original image and free handles
img.Dispose();
// Delete the original file
File.Delete(imgPath);

答案 2 :(得分:0)

在删除图片之前将yourPictureBox.image设置为null