Image.Fromfile() keeps file open

  • Thread starter Thread starter Peter R. Fletcher
  • Start date Start date
P

Peter R. Fletcher

I have written an application that is chained to by another
application (not written by me) to print some temporary graphics files
produced by the first application. Once the files have been printed
they are of no further use to me, and I would like to be able to
delete them. I am using DrawImage(Image.FromFile(strFilename)) in the
PrintPage handler to print the images, and this aspect of the program
is working fine.

All the code described below is "behind" a single form:

After the images are printed (and the PrintDocument Object that
handles this has been explicitly set to Nothing), I call a separate
Sub to delete the files. The attempted Delete throws a "Cannot access
file because another process is using it" exception. By
experimentation, I have determined that the "other process" is related
to the previous Image.FromFile() call, even though this should
obviously no longer be active. If that call is removed from the
PrintPage handler (and replaced by a DrawString call so that the Print
still has something to do), the subsequent Delete proceeds without
problems. No other process is or could be accessing the file (please
believe that I really have thoroughly checked this!), and I have tried
(without success) waiting for long periods of time (multiples of 10
seconds) after completing the print and before trying to delete the
file, in case some slow asynchronous system process related to the
print was taking a while to complete.

Has anyone seen anything like this before?
 
Thanks! I'm glad I'm not losing it! Is this anything other than a
straightforward bug in the Framework?
 
Peter,
Is this anything other than a straightforward bug in the Framework?

Actually I think it's considered to be "by design". I don't remember
the exact reasoning, but the issue has come up many times before in
the microsoft.public.dotnet.framework.drawing group. So if you search
that using Google Groups, you might find more details.



Mattias
 
It is as you say. Something about keeping the image in case you want
to use another bit of it!. I am not convinced that this makes sense
when you have explicitly deleted all references to any objects which
reference the file! Your workaround is excellent, though.
 
Back
Top