Consider the 3 versions of file creation below, for various reasons I have different methods to add files sent from a Windows Forms application (using HttpClient) to an ASP.NET Core 2.2 web application.
Quite simply I create a file on the file system and then immediately create a thumbnail image if the file is an image type file (extensions are in the files
array).
When I run this locally all is fine, images and thumbnails (where applicable) get created. However, when I run this deployed I get no thumbnails. ScaleImage
won't create a thumbnail if it can find a file and will return an empty string.
It's a timing thing I think but has anyone come across this before?
//v1
await File.WriteAllBytesAsync(filePath, Convert.FromBase64String(result.Data));
string thumbnail = files.Contains(sFileExt) ? SystemFunctions.ScaleImage(filePath, 192, 192) : "";
//v3
await file.CopyToAsync(stream);
string thumbnail = files.Contains(sFileExt) ? SystemFunctions.ScaleImage(filePath, 192, 192) : "";
//v3
await writer.WriteAsync(result.Data);
writer.Close();
string thumbnail = files.Contains(sFileExt) ? SystemFunctions.ScaleImage(filePath, 192, 192) : "";
ScaleImage function
//create a thumbnail file from the supplied image respecting the aspect ratio
//returns the path the the thumbnail or empty string if the thumbnail can't be
//created for some reason
internal static string ScaleImage(string fileName, int maxWidth, int maxHeight)
{
if (File.Exists(fileName))
{
try
{
Image oImage = Image.FromFile(fileName);
double dRatioX = (double)maxWidth / oImage.Width;
double dRatioY = (double)maxHeight / oImage.Height;
double dRatio = Math.Min(dRatioX, dRatioY);
int iNewWidth = (int)(oImage.Width * dRatio);
int iNewHeight = (int)(oImage.Height * dRatio);
Image oNewImage = new Bitmap(iNewWidth, iNewHeight);
Graphics.FromImage(oNewImage).DrawImage(oImage, 0, 0, iNewWidth, iNewHeight);
string filePath = Path.GetDirectoryName(fileName);
string fileExt = Path.GetExtension(fileName);
string newFileName = Guid.NewGuid().ToString();
newFileName = Path.Combine(filePath, $"{newFileName}{fileExt}");
oNewImage.Save(newFileName);
WriteToErrorLog(newFileName);
return newFileName;
}
catch (Exception e)
{
var stackFrame = new System.Diagnostics.StackTrace(e, true);
var frame = stackFrame.GetFrame(0);
var line = frame.GetFileLineNumber();
WriteToErrorLog($"Error: {e.Message}({line}) [{frame.GetMethod().Name}]: {fileName}\r\n{e}");
return "";
}
}
WriteToErrorLog($"File Not Found: {fileName}");
return "";
}