-1

I am trying to save an image I've created from Bitmap in a given Path in my project, but I get this error: Additional information: A generic error occurred in GDI+.

This is the code :

        public void SaveCaptchaImage(string name)
        {
            Bitmap image = new Bitmap(128, 64);
            string path = "/content/images";

            if (System.IO.File.Exists(path + name))
                System.IO.File.Delete(path + name);

            using (Pen myPen = new Pen(Color.Red, 5))
            using (Brush myBrush = new SolidBrush(Color.Silver))
            using (Font myFont = new Font("Arial", 16))
            using (Graphics graphObject = Graphics.FromImage(image))
            {
                graphObject.FillRectangle(myBrush, new Rectangle(0, 0, 128, 64));
                graphObject.DrawString(GetRandomCaptcha(), myFont, myBrush, new Point(20, 20));
                image.Save(path + name + ".png", ImageFormat.Png);
            }
            image.Dispose();
        }

The exception occurs at this line:

image.Save(path + name + ".png", ImageFormat.Png);

What can I do to solve this problem ?

Edit: I don't get why I got downvoted, but ok.

Marcus
  • 128
  • 2
  • 12
  • I suggest you always use `Path.Combine` to combine paths rather than just concatenating the strings - because unless `name` starts with a slash, you're going to end out with `image.Save("pathname.png", ImageFormat.Png);` rather than `image.Save("path/name.png", ImageFormat.Png);` – stuartd Aug 22 '16 at 15:05

1 Answers1

0

Wrap your path with Server.MapPath like:

image.Save(HttpContext.Current.Server.MapPath(Path.Combine(path, name + ".png")), ImageFormat.Png);

to get absolute path instead of relative.

and use Path.Combine method like @stuartd suggested in comments.

serhiyb
  • 4,753
  • 2
  • 15
  • 24