Re: Dispose

Adam Sills <[email protected]> Wed, 11 Jul 2007 22:59:39 -0500
Newsgroups gmane.comp.windows.devel.dotnet.web
Message-ID <[email protected]>
You shouldn't touch any other managed objects inside a class finalizer. Your
Photo reference could be finalized before the object in question is and it'd
never delete the temp file.

What you should do instead is load the image from memory so it doesn't lock
any files.

1. Create the image in the temp directory
2. Use File.ReadAllBytes to get a byte[] of your file (or if you're .NET
1.1, do it the long way)
3. Delete the temp image
4. Put the bytes from #2 in a MemoryStream using the ctor that takes a
byte[]
5. Use Image.FromStream to open your image

Then you don't have to worry about any cleanup as .NET will do it all for
you.

Adam..

-----Original Message-----
From: Discussion of building .NET applications targeted for the Web
[mailto:[email protected]] On Behalf Of Andrew Dunn
Sent: Wednesday, July 11, 2007 8:57 PM
To: [email protected]
Subject: [DOTNET-WEB] Dispose

Hi,

Can anyone see a better way of doing this. I have a class that holds an
image as one of it's properties. This image is held in the windows temp
directory. I want to delete it when the class is destroyed. Is Dispose
the best place to do this? Is ~PatientPhoto() OK to call dispose?




public Bitmap Photo
{
    get{ return _Photo;}
    set{ _Photo = value;}
}

~PatientPhoto()
{
    Dispose();
}

public void Dispose()
        {
            if(Photo != null)
            {
                if (Photo.Tag != null)
                {
                    string FileLoc = Photo.Tag.ToString();

                    ///Delete the photo file as it is stored in a
temporary file in the windows temp directory
                    if (File.Exists(FileLoc))
                    {
                        Photo.Dispose();
                        Photo = null;

                        try
                        {
                            File.Delete(FileLoc);
                        }
                        catch (IOException e)
                        {

System.Windows.Forms.MessageBox.Show(e.Message);
                        }
                    }
                }
            }

        }

===================================
This list is hosted by DevelopMentor.  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com