views:

20

answers:

3

In asp.net, we have uploaded a .jpeg file and saved this as bitmap image using following code

HttpPostedFile uploadFile; System.IO.Stream stream = uploadFile.InputStream;

 using (System.Drawing.Image imgSource = System.Drawing.Bitmap.FromStream(stream))
{
    System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

    using (System.Drawing.Image imgThumbnail = imgSource.GetThumbnailImage(imgSource.Width, imgSource.Height, myCallback, IntPtr.Zero))
    {

       imgThumbnail.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);

        imgThumbnail.Dispose();
    }
    imgSource.Dispose();
}

stream.Close();
stream.Flush();
stream.Dispose();

After upload, if we perfrom delete operation it throws error.
We are following code to do so;

if (File.Exists(filePath))
{
     File.Delete(filePath);

}


The exception says:The process cannot access the file 'abc.jpg' because it is being used by another process.

Does anyone know, why this is happening ?
Thanks in advance.

A: 

How about trying first flushing and then closing the stream?

ajay_whiz
A: 

Also:

  • The using construct takes care of calling Dispose() for you. You don't need to do it explicitly, and in fact, doing so might break improperly implemented IDisposables.
  • Are you absolutely sure that filename is different each time? If not, concurrent requests may overwrite each others' files, so the exception you're getting may be caused by one thread trying to delete the file while another is overwriting it.
tdammers
A: 

The garbage collector doesn't release it's resources to your file immediately.

You can try and run GC.Collect() to "force" the garbage collector to do it's thing. Do this after you have Disposed your file and before you try and delete it.

Edit: I you have some anti virus software on your machine it's likely that it is what is using your file. Same if you have an Explorer window open to the folder where the image is created etc.

Jesper Palm
Thanks Jesper :)The first option worked for me.
Vijay Balkawade