Search code examples
c#fileseleniumpathscreenshot

A generic error occurred in GDI+ (screenshot SaveAsFile, ExternalException)


Hello I tried looking through questions that may have my answer but none of them did.

I am doing web automation testing and trying to take a screenshot of when an error occurs and save it to a file in another folder.

My program has a 30 second timeout when searching for elements on the page. If after 30 seconds no element is found, it takes a SS, reloads the page, and tries again.

The first screenshot works fine. But on the second run through, it tries to save another screenshot to the folder and I get this incredibly vague error that is seemingly caused by a hundred different things, so I'm not quite sure what the problem is.

Here's my code:

public void takeScreenShot()
    {
        string ssPath = _persistencePath += "\\Errors";

        string currTime = DateTime.Now.ToString(@"MMM-ddd-d-HH.mm");

        Screenshot ss = ((ITakesScreenshot)_driver).GetScreenshot();

        try
        {
            ss.SaveAsFile(ssPath + "\\ERROR-" + currTime + ".png", System.Drawing.Imaging.ImageFormat.Png);
            ssCount = 0;
        }
        catch (System.Runtime.InteropServices.ExternalException)
        {
            ssCount++;

            //error occurs here
            ss.SaveAsFile(ssPath + "\\ERROR-" + currTime + "(" + ssCount + ")" + ".png", System.Drawing.Imaging.ImageFormat.Png);
        }

I initially thought the issue was that it was trying to save a file of the same name, because if the error happens during the same minute then the file name is the same. So that's why I added that catch block, in an attempt to change the name if it occurs in the same minute. But that didn't fix it.

Again I tried searching all over and couldn't find an answer. Any help is greatly appreciated.


Solution

  • Well, if anyone's curious I solved it. Turns out I'm just an idiot.

    string ssPath = _persistencePath += "\\Errors";
    

    this line was appending another \Errors to the target path on the second run though. thus invalidating the path, because \Errors\Errors didn't exist.

    Thanks to everyone who commented/tried to help!