I have a simple alert form which pops up, and I'm trying to have different messages depending on a colour of a pixel in an image, the alerts' load code is is:
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;
}
Regardless of where the File.Delete line is, I get the message that the file is in use, and can't be deleted.
I've had this issue before using FileSystemWatcher where I couldn't delete the file as it was still being used, and I had to stop the watcher, but in this situation I don't know how to solve it.
The file starts being used here:
Bitmap myBitmap = new Bitmap(Properties.Settings.Default.AlertFile);
I've tried adding:
myBitmap.Dispose();
But I still get the message it is in use.
Edit:
Fixed with Using
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 :(";
}
}
Try adopt Using Statement that provides a convenient syntax that ensures the correct use of IDisposable
objects like File
or Bitmap
.
This is the correct syntax: you don't need to call .Dispose
on 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 :(";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.