We have an application at work that pulls images from a proprietary binary file and saves them to a local directory. The directory path and filename on the local machine are built on the fly based on client information. The application went through a full round of testing and passed all cases. However, when we moved the application to production and ran it against live data we ran into the following error:
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+
We spent most of the day trying to track down the error, but nothing I found on the Internet gave a clue. First we thought that perhaps we were getting image data in a format that we didn't expect (i.e. loading JPEG data and saving it as a TIFF file), but that wasn't it. Finally, we tried writing the raw data out to disk using a FileStream instead of Image.Save(). This did not solve the problem, but it produced a different Exception that pointed us in the right direction. The new Exception stated something similar to the message below:
"Could not find part of the path 'C:\TEMP\2345\111299\Bin1\Slot3\Company.Bin1\Slot3.PartNumber_1.TIFF'"
The clue came in the last part of the message. The path format was supposed to be:
<Root_Dir><CompanyID><FranchiseID><StorageSection><FileName>.TIFF
where...
<FileName> = <CompanyID>.<StorageSection>.<PartNumber>.TIFF
Looking closely we discovered that our path was including a <StorageSection> that had a backslash in the name (i.e. "Bin1\Slot3"). Therefore, when .NET tried to create a file with the name "Company.Bin1\Slot3.PartNumber_1.TIFF" an Exception was thrown.
A simple one line change to our application fixed the issue by cleaning up the file name before attempting to save the file:
// Ensure that we have a safe filename
strFileNamePrefix = Regex.Replace(strFileNamePrefix, @"[\\/\?\:\<\>\|\*]", "_");
Hopefully the above will help you save more time than it took us to figure this out.