tags:

views:

88

answers:

3
+1  Q: 

Delete Image

Hi All, I am using asp.net C#. I am saving image file in the folder and deleting it.When i am deleteing it gives error "The process cannot access the file 'C:\Inetpub\wwwroot\Admin\Temp\visible_Jul-13-2009_035606.png' because it is being used by another process"

Please Help

Code:

fupAddImage.PostedFile.SaveAs(Server.MapPath("Temp") + @"\" + tempFilename);
File.Delete(Server.MapPath("Temp") + @"\" + tempFilename);
+1  A: 

How do you save the image? Have you made sure that you dispose all Image and Stream objects that are used for saving the image? Since both Image and Stream (and StreamWriter) implement IDisposable you should make sure to call Dispose (or set up using blocks when creating the objects) so that the file is properly closed when the image has been saved.

Update: One thing that you could try is to save the image data yourself, in order to gain more control over exactly how it is done:

private static void SaveFile(Stream input, string fileName)
{
    using (Stream output = File.OpenWrite(fileName))
    {
        byte[] buffer = new byte[8192];
        int bytesRead;
        do
        {
            bytesRead = input.Read(buffer, 0, buffer.Length);
            output.Write(buffer, 0, bytesRead);
        } while (bytesRead == buffer.Length);
    }
}

// Pass the uploaded file data to the above method like this:
SaveFile(fupAddImage.FileContent, Path.Combine(Server.MapPath("Temp"), tempFilename))
Fredrik Mörk
What was the downvote about? If there are any errors in my sample it would be great to know so it can be fixed...
Fredrik Mörk
Not sure - looks good to me. +1
lc
+1  A: 

You need to post some code to know for sure, but the file is probably still open somewhere and thus your application hasn't released the file lock yet. Try closing any open streams and disposing of any file handles pointing to the object before you delete it.

You may also need to wait for the OS to release the file after disposing of all handles pointing to it.

I'm guessing the problem is the above. If you're creating a file and deleting it in the next line, the OS probably hasn't even flushed the file to disk yet, let alone released the file handle and the lock. Try giving some time between the write and delete and see if you can delete it again.

lc
A: 

try typing in:

openfiles file_path_and_filename

in command prompt (cmd.exe) to find the reason.

and also ensure you have delete access.

waqasahmed