繁体   English   中英

创建了一个位图变量以获取像素颜色,如何停止使用该文件,以便可以将其删除。

[英]Created a bitmap variable to get a pixel colour, how do I stop using the file so I can file.delete it

我有一个简单的警报表单会弹出,并且我尝试根据图像中像素的颜色发送不同的消息,警报的加载代码为:

        private void Alert_Load(object sender, EventArgs e)
        {
            Bitmap myBitmap = new Bitmap(Properties.Settings.Default.AlertFile);
            Color pixelColor = myBitmap.GetPixel(50, 50);
            File.Delete(Properties.Settings.Default.AlertFile);

            if (pixelColor == Color.FromArgb(255, 237, 28, 36))//red
            {
                AlertMessage.Text = "Test Message 1: It is Red";
            }
            else
            {
                AlertMessage.Text = "Test Message 2: It isn't Red";
            }

            TopMost = true;
        }

无论File.Delete行在什么位置,我都会收到以下消息:文件正在使用中,无法删除。

我在使用FileSystemWatcher之前遇到了这个问题,在该情况下我无法删除该文件,因为该文件仍在使用中,我不得不停止观察程序,但是在这种情况下,我不知道如何解决它。

该文件在这里开始使用:

        Bitmap myBitmap = new Bitmap(Properties.Settings.Default.AlertFile);

我尝试添加:

myBitmap.Dispose();

但是我仍然收到消息,它正在使用中。

编辑:

固定使用

            Color pixelColor;
            using (var AlertImage = new Bitmap(Properties.Settings.Default.AlertFile))
            {
                pixelColor = AlertImage.GetPixel(50, 50);
                AlertImage.Dispose();
                File.Delete(Properties.Settings.Default.AlertFile);

                if (pixelColor == Color.FromArgb(255, 237, 28, 36))
                {
                    AlertMessage.Text = @"It was Red :)";
                }
                else
                {
                    AlertMessage.Text = @"It was not Red :(";
                }
            }

尝试采用using语句 ,该语句提供了方便的语法,可确保正确使用IDisposable对象(如FileBitmap

这是正确的语法:不需要在.Dispose上调用AlertImage

Color pixelColor;

using (var AlertImage = new Bitmap(Properties.Settings.Default.AlertFile))
{
    pixelColor = AlertImage.GetPixel(50, 50);
}

File.Delete(Properties.Settings.Default.AlertFile);

if (pixelColor == Color.FromArgb(255, 237, 28, 36))
{
    AlertMessage.Text = @"It was Red :)";
}
else
{
    AlertMessage.Text = @"It was not Red :(";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM