Runtime: Bitmap.Save 'A generic error occurred in GDI+

Created on 1 Nov 2019  路  10Comments  路  Source: dotnet/runtime

when calling bitmap.Save with a file path where the folder doesn't exist the save method throws a
System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.'

IMHO the the folder should be created (to match folder file operations) or throw an expection of DirectoryNotFoundException

area-System.Drawing untriaged up-for-grabs

All 10 comments

Seems reasonable - do you want to offer a PR? We would want the same behavior on Unix and Windows, but if the directory was created in the .NET code, that would hopefully be true.

Seems reasonable to me as well.

I can look into that.

As a user I would expect an exception being thrown if I supplied a non-existing path. Creating folders is a side effect that might hide errors and lead to unexpected behavior.
Please consider changing the current exception to a DirectoryNotFoundException rather than trying to create the full path.

What do other API do?

@danmosemsft File.Create creates the folder/directory structure

@Backhage I agree with that. If the API change is approved, maybe later an optional bool param can be passed to indicate whether to create a non-existing path - but IMO it's out of scope of this issue.

@grahamehorner At least for me, using .NET Core 3.0 on Windows, File.Create(@"C:TempNonExistingPathFile.tmp"); throws a DirectoryNotFoundException.

@Backhage interesting that differs to my experiance with .NET 2.2 and yes your correct, .NET 3.0 throws the exception as I would have expected; Directory.Create also creates the directory tree?

The root of this issue is that Image.Save calls GdipSaveImageToFile, which is implemented natively. The only way to solve this issue is to introduce a new exception by doing the directory path check earlier. This check could potentially be moved, and only performed before the call to GdipSaveImageToFile, but it would then lead to a potential difference when the code paths diverge in Save(Stream stream, ImageCodecInfo encoder, EncoderParameters? encoderParams) when _rawData vs non-null.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nalywa picture nalywa  路  3Comments

EgorBo picture EgorBo  路  3Comments

matty-hall picture matty-hall  路  3Comments

chunseoklee picture chunseoklee  路  3Comments

noahfalk picture noahfalk  路  3Comments