0

I'm trying to take a screenshot of the screen in C# Windows Forms. Code (from https://www.c-sharpcorner.com/UploadFile/2d2d83/how-to-capture-a-screen-using-C-Sharp/):

Bitmap captureBitmap = new Bitmap(1600, 900, PixelFormat.Format32bppArgb);
Rectangle captureRectangle = Screen.AllScreens[0].Bounds;
Graphics captureGraphics = Graphics.FromImage(captureBitmap);
captureGraphics.CopyFromScreen(captureRectangle.Left, captureRectangle.Top, 0, 0, captureRectangle.Size);
captureBitmap.Save(@"C:\Screenshot.jpg", ImageFormat.Jpeg);

It throws this error: A generic error occured in GDI+ (in captureBitmap.Save). What can I do? I tried using captureBitmap.Dispose() but it still doesn't work.

  • Does this answer your question? [A Generic error occurred in GDI+ in Bitmap.Save method](https://stackoverflow.com/questions/15862810/a-generic-error-occurred-in-gdi-in-bitmap-save-method) – Sinatr May 28 '21 at 09:17
  • Thank you, but now it's showing "Access to the path 'C:\Users\Admin\Desktop\Capture.jpg' is denied.". I tried changing the path, but it doesn't work. – Dogramming May 28 '21 at 09:26
  • Update: if I save it to one of my pendrives, it works. – Dogramming May 28 '21 at 09:39
  • 1
    C: root is a system path. You can write there only if running with administrative privileges. As a general rule, never write arbitrary files in a system path; prefer use of temporary folder (`Environment.ExpandEnvironmentVariables("TEMP")`) or user owned folder (`Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)`). – Rubidium 37 May 28 '21 at 10:27

1 Answers1

0

You can replace your last line

captureBitmap.Save(@"C:\Screenshot.jpg", ImageFormat.Jpeg);

to

string outputFileName = @"C:\Screenshot.jpg";
using (MemoryStream memory = new MemoryStream())
{
    using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
    {
        captureBitmap.Save(memory, ImageFormat.Jpeg);
        byte[] bytes = memory.ToArray();
        fs.Write(bytes, 0, bytes.Length);
    }
}

Reason and LINK for further read