图片删除c#winform

时间:2016-08-25 15:05:13

标签: c# winforms

我的计算机上有一个我的程序使用的图像(将其加载到pictureBox) 在运行时!尝试从我的电脑中删除图片,
但有一个错误,说图像是开放的母鸡为什么它不能是 删除。
我试过这段代码但是没有用

PICbefore.Image = new Bitmap(Image.FromFile(ofd.FileName));
ProfilePic.Image = null;
File.Delete("C:\image.jgp");

3 个答案:

答案 0 :(得分:1)

将PictureBox的Image设置为null不会删除任何内容。它将导致PictureBox停止显示它,但是图像仍将存在于内存中,直到将来运行垃圾收集时的某个任意点。你需要处理图像对象。

PICbefore.Image = new Bitmap(Image.FromFile(ofd.FileName));
Image img = ProfilePic.Image;
ProfilePic.Image = null;
img.Dispose();
File.Delete("C:\image.jgp");

如果您丢弃当前正在保存的图像,我不确定PictureBox会做什么,所以为了安全起见我在处理之前将其从PictureBox中删除。处理完毕后,您应该能够删除该文件。

答案 1 :(得分:1)

我之前遇到过这种情况。从内存中,解决方案是打开一个流来读取文件(使用using语句),然后通过流加载位图并分配它。这样您就可以完全控制文件/流的生命周期,ProfilePic.Image属性永远不会触及文件。

    var filename = @"c:\image.png";
    Image img;
    using (var stream = File.OpenRead(filename))
    {
        img = new Bitmap(stream);
    }
    PICbefore.Image = img;
    File.Delete(filename);

答案 2 :(得分:0)

我最近不得不处理我认为你遇到的问题。这对我有用(虽然实际上这是WPF项目 - 所以在你的Winform应用程序中可能并不完全相同)。我认为img.freeze()是关键部分。

 if (File.Exists(filePathName))
            {
                // read the file this way to open as read-only and cache the image in memory for use rather than keeping it open/locked and preventing updates to it
                BitmapImage img = new BitmapImage();
                using (FileStream fs = File.OpenRead(filePathName))
                {
                    img.BeginInit();
                    img.CacheOption = BitmapCacheOption.OnLoad;
                    img.StreamSource = fs;
                    img.EndInit();
                    img.Freeze();
                }

                gridChartBg.Background = new ImageBrush(img);
            }