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+
error.
///<summary>
/// Grabs a screen shot of the App and saves it to the C drive in jpg
///</summary>
private static String GetDesktopImage(DevExpress.XtraEditors.XtraForm whichForm)
{
Rectangle bounds = whichForm.Bounds;
// This solves my problem but creates a clutter issue
//var timeStamp = DateTime.Now.ToString("ddd-MMM-dd-yyyy-hh-mm-ss");
//var fileName = "C:\\HelpMe" + timeStamp + ".jpg";
var fileName = "C:\\HelpMe.jpg";
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(fileName, ImageFormat.Jpeg);
}
return fileName;
}
A function like this will do it:
Stick it in a
while
loop and you have something which will block until the file is accessible:If you check access before writing to the file some other process might snatch the access again before you manage to do your write. Therefor I would suggest one of the following two:
getting a stream
then use it like this:
retry scope
and then use WithRetry(() => File.WriteAllText(Path.Combine(_directory, name), contents));
There is no function out there which will allow you to wait on a particular handle / file system location to be available for writing. Sadly, all you can do is poll the handle for writing.
You can let the System wait, until the process is closed.
Just as simple as this:
Process.Start("the path of your text file or exe").WaitForExit();
Taking the top answer I wrote a similar one, but it's async, non-blocking, awaitable, cancelable (just stop the task) and checks the exception thrown.
You can use it in this fashion:
If you have to really wait for it, or in a more JS-promise-way: