title: A GDI+ error sometimes happening while making a screenshot
body: <p>We have a bit of code which makes screenshot during error reporting. The application is WinForms in .NET 4 framework and is run on Windows Terminal Server. The app is used concurrently via the rdp connection. The code is fairly old and sometimes it gives the following error:</p>
  
  <blockquote>
    <p>ExternalException: A generic error occurred in GDI+.</p>
    
    <p>Stack: WinBase.PrikazIznimke.NapraviScreenShot()
    WinBase.PrikazIznimke.button1_Click(Object sender, EventArgs e)</p>
    
    <p>Inner exception stack: System.Drawing.Image.Save(String filename,
    ImageCodecInfo encoder, EncoderParameters encoderParams)
    WinBase.PrikazIznimke.NapraviScreenShot() Stack:
    WinBase.PrikazIznimke.NapraviScreenShot()
    WinBase.PrikazIznimke.button1_Click(Object sender, EventArgs e)</p>
    
    <p>Inner exception stack: System.Drawing.Image.Save(String filename,
    ImageCodecInfo encoder, EncoderParameters encoderParams)
    WinBase.PrikazIznimke.NapraviScreenShot().</p>
  </blockquote>
  
  <p>The reasons for this error we never understood, we investigated several times without conclusion. The error itself is rarely encountered (maybe 1% of total reports). The code in full is this one:</p>
  
  <pre><code>private void NapraviScreenShot()
  {
      try
      {
          Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
  
          Graphics graphics = Graphics.FromImage(bitmap);
          graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
  
          this.ObrisiScreenShot(); 
  
          bitmap.Save(Application.UserAppDataPath + @"greska.jpeg", ImageFormat.Jpeg);
      }
      catch (Exception ex)
      {
          bool rethrow = ExceptionPolicy.HandleException(ex, "Logiraj i proslijedi");
          if (rethrow)
              throw;
      }
  }
  
  private void ObrisiScreenShot()
  {
      try
      {
          string put = Application.UserAppDataPath;
          if (System.IO.File.Exists(put + @"greska.jpeg") == true)
              System.IO.File.Delete(put + @"greska.jpeg");
      }
      catch (System.IO.IOException) 
      {
          return;
      }
      catch (Exception ex)
      {
          bool rethrow = ExceptionPolicy.HandleException(ex, "Logiraj i proslijedi");
          if (rethrow)
              throw;
      }
  }
  </code></pre>
  
  <p>If you have any ideas what we could do next or any theories why would the error happen I would be grateful. </p>