简体   繁体   中英

A generic error occurred in GDI+ exception when saving bitmap

I'm trying to save a file in my project bin folder. For some reason when I give it a string as a path such as

string filePath = @"C:\Users\Craig\Documents\Visual Studio 2015\Projects\CreateTextExample\CreateTextExample\bin\ErrorLog";
Thread.Sleep(100);
bitmap.Save(filePath+@"\ErrorImage.Bmp", ImageFormat.Bmp);

it saves the file fine. However when I try and save it like

string filePath = System.IO.Directory.GetCurrentDirectory() + @"\ErrorLog";
Thread.Sleep(100);
bitmap.Save(filePath+@"\ErrorImage.Bmp", ImageFormat.Bmp); 

I get a runtime error saying A generic error occurred in GDI+

Not sure why this is happening. Initially I thought it may have been the folder permissions however this doesn't seem to be the case as it works using the first method. 在此处输入图片说明

Any ideas why this is happening?

My code is as follows

string currentContent = String.Empty;

bitmap = new Bitmap(System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width, System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap as Image);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

string filePath = System.IO.Directory.GetCurrentDirectory() + @"\ErrorLog";
Thread.Sleep(100);
bitmap.Save(filePath+@"\ErrorImage.Bmp", ImageFormat.Bmp);

When using the Save method of the Bitmap you should ensure that the directory exist. In the first case your directory is this:

This directory should exist in your system

C:\\Users\\Craig\\Documents\\Visual Studio 2015\\Projects\\CreateTextExample\\CreateTextExample\\bin\\ErrorLog

But in the second case (when using Directory.GetCurrentDirectory method) your directory should be something like this (it may have a extera Debug or Release folder before the ErrorLog )

These directories should not exist in your system (depending you are in Debug or Release Mode)

C:\\Users\\Craig\\Documents\\Visual Studio 2015\\Projects\\CreateTextExample\\CreateTextExample\\bin\\Debug\\ErrorLog

C:\\Users\\Craig\\Documents\\Visual Studio 2015\\Projects\\CreateTextExample\\CreateTextExample\\bin\\Release\\ErrorLog

So bitmap.Save throws error because the directory does not exists in your system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM