views:

143

answers:

3

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;
    }
+1  A: 

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.

JaredPar
+1  A: 
bool isLocked = true;
while (isLocked)
 try {
  System.IO.File.Move(filename, filename2);
  isLocked = false;
 }
 catch { }
 System.IO.File.Move(filename2, filename);
tsilb
+4  A: 

A function like this will do it:

    public static bool IsFileReady(String sFilename)
    {
        // If the file can be opened for exclusive access it means that the file
        // is no longer locked by another process.
        try
        {
            using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
            {
                if (inputStream.Length > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
        }
        catch (Exception)
        {
            return false;
        }
    }

Stick it in a while loop and you have something which will block until the file is accessible

Gordon Carpenter-Thompson
Thanks! I threw this in there ` var isReady = false; while (!isReady) { isReady = IsFileReady(fileName); }`and all seems well.
Refracted Paladin