0

I have a dialog box in a C# Winforms application. I want to save images. But each time I click on the save button, I get an error

A generic error occurred in gdi+

This is my code for saving the image:

var SavedFileName = string.Format(@"{0}.png", Guid.NewGuid());

var path = Application.StartupPath + "/passport/" + SavedFileName.ToString();

if(passportsize.Image == null)
{
    SavedFileName = "";
}
else
{
    passportsize.Image.Save(path,System.Drawing.Imaging.ImageFormat.Png);
}
9
  • Does the directory exist? Commented Dec 13, 2018 at 21:25
  • Not at the moment Commented Dec 13, 2018 at 21:26
  • That's probably the problem. Commented Dec 13, 2018 at 21:29
  • 3
    Unrelated: notice that the .ToString on SavedFileName is redundant since it is already a string. And I would recommend using Path.Combine to construct the file path. Specifically var path = Path.Combine(Application.StartupPath, "passport", SavedFileName);. Are you using Linux or Windows? Commented Dec 13, 2018 at 21:32
  • 3
    Also, Application.StartupPath is a very bad place to try to save a file; it's probably not writable by non-admins, and will get deleted if you uninstall or repair your application. Save user data in Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData). Commented Dec 14, 2018 at 0:43

2 Answers 2

1

Try using a back slash instead of a forward slash. "\\passport\\" instead of "/passport/"

Sign up to request clarification or add additional context in comments.

4 Comments

That won't compile.
You will need to escape the backslashes by doubling them
@Hans Indeed, I was prompting Terry to do improve the answer.
Thanks @John. Getting both of them to show up was a little tricky.
0

You haven't provided the full message, so I can't be sure, but it's likely that the source stream that created the image has been disposed of but the image is still tied to it.

When you create the image, you should clone it. For example:

private Image ImageFromBytes(byte[] imageBytes)
{
    using (var ms = new MemoryStream(imageBytes))
    {
        using (var image = Image.FromStream(ms))
        {
            return (Image)image.Clone();
        }
    }
}

Then when you come to save it later, you shouldn't encounter any issues.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.