SEARCH:   GO
{Blog entries}
Jan 28

Written by: Javier Callico
1/28/2010 

Today, when writing a function that opens an image, adds a simple text on the top corner and streams the resulting image to the client I noticed that the original image used as template couldn't be renamed or deleted after the code ran for the first time and for as long as the web application remained running. Restarting the web application makes the problem to go away until of course the offending code runs again.

This is clearly an indication that the code is leaving handles to the original file unclosed which are only released when the application is terminated. After verifying with Process Explorer (a must have tool by the way) that indeed a handle to the file remained open. I modified my code to dispose the instances of Bitmap, Image and Graphics I was using. Surely enough disposing the Graphics instance did the trick. 

This is how my code looked after the fix:

using (Image image = new Bitmap("test.png"))
{
    // this using solved the problem
    using (Graphics g = Graphics.FromImage(image))
    {
        /* your code here */
    }
}

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel