I've tried so many different ways to do this, and it's still telling me the file is in use when I try to delete it before saving it again.
if (Clipboard.GetDataObject().GetData(DataFormats.Bitmap) != null)
{
if (File.Exists(filename)) { File.Delete(filename); }
using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite))
{
ImageConverter converter = new ImageConverter();
byte[] bytes = (byte[])converter.ConvertTo(Clipboard.GetDataObject().GetData(DataFormats.Bitmap), typeof(byte[]));
fs.Write(bytes, 0, bytes.Length);
fs.Close();
fs.Dispose();
}
}
As you can see, I have everything in a "using" block. I also "close" the file, and even tried explicitly calling the "dispose" as well. But when I run the code again, it STILL tells me the file is in use. What can I do to be able to overwrite the file?
I've also tried it this way:
using (Bitmap bmp = new Bitmap((Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap)))
{
if (bmp != null)
{
if (File.Exists(filename)) { File.Delete(filename); }
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite))
{
bmp.Save(memory, ImageFormat.Bmp);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
memory.Dispose();
}
bmp.Dispose();
break;
}
}
and it still gives me the same error.