When is it safe to delete the original image file in .Net?

When using the code below, I sometimes get the error "A general error has occurred in GDI +. On System.Drawing.Image.Save". I started to believe that this is because I am deleting the original image before saving the newly created image. This is true? When is it really safe to delete the original image file, then?

Subclass:

thumbnailImage = GetThumb();
thumbnailImage.Save(fullDestinationFilename);

      

Base class:

public virtual Image GetThumb() {
    using (var image = Image.FromFile(sourceFile)) {
        thumbImage = Crop(image, BrowserWidth, BrowserHeight));
    }
    File.Delete(sourceFile);
    return thumbImage;
}

private static Image Crop(Image image, int width, int height) { 
    var croppedImage = new Bitmap(width, height);
    using (var g = Graphics.FromImage(croppedImage)){
        g.DrawImage(image, 0, 0, image.Width, image.Height);
       return croppedImage;
   }

      

}

+3


source to share


2 answers


I think I need to work now. The problem was not with the code I showed you. After saving the thumbnail to a file, I wrote it to the http response stream and did NOT DELETE the thumbnail image. When another request came up that resulted in this file being saved, it was unable to overwrite the image file as it was still blocked from the last request.



0


source


Have you tried something like this

public virtual Image GetThumb() {
    using (var image = Image.FromFile(sourceFile)) {
        thumbImage = Crop(image, BrowserWidth, BrowserHeight));
    }
    if(thumbImage != null)
    {     
      File.Delete(sourceFile);
    }
    return thumbImage;
}

      



Also I think it is better to use try catch .

-1


source







All Articles