How do I wait for the file to be free so that ss.Save()
can overwrite it with a new one? If I run this twice close together(ish), I get a generic GDI+
The problem is that your code is already opening the file by calling File.Create
, which returns an open file stream. Depending on timing, the garbage collector may have noticed that the returned stream is unused and put it on the finalizer queue, and then the finalizer thread may have cleaned things up up already before you start writing to the file again. But this is not guarantueed, as you noticed.
To fix it, you can either close the file again immediately like File.Create(...).Dispose()
. Alternatively, wrap the stream in a using statement, and write to it.
using (FileStream stream = File.Create(fileName))
using (Bitmap ss = new Bitmap(bounds.Width, bounds.Height))
using (Graphics g = Graphics.FromImage(ss))
{
g.CopyFromScreen(whichForm.Location, Point.Empty, bounds.Size);
ss.Save(stream, ImageFormat.Jpeg);
}