Inside Man
Inside Man

Reputation: 4305

File In Use - Can not Delete or Replace - ASP.Net

I need to replace pictures in my server, User will select a picture from list box then He will select a picture from his PC and then He will click on Replace button to Do the process, Also the uploaded file will resize to old file's dimension. After this Resize the uploaded file should delete and the new image should save on server (overwriting the image which is selected in listbox). Here is the Replace Button's Code Behind:

protected void Button1_Click(object sender, EventArgs e)
{
    // Save Selected Picture into Server
    string file = Server.MapPath("~/Resources/").ToString() + UploadPic.PostedFile.FileName.ToString();
    UploadPic.PostedFile.SaveAs(file);
    // Resize The Picture in Server
    Bitmap image = new Bitmap(file);
    Bitmap picture = new Bitmap(ListBox1.SelectedItem.Value);
    image = ResizeImage(image, picture.Width, picture.Height);
    // Saving the New Picture in Server
    File.Delete(file);
    image.Save("~/Resources/" + Path.GetFileName(ListBox1.SelectedItem.Value));
}

But It seems Both uploaded file and the image which is selected from listbox is in use, I tried disposing so many things such as ListBox,UploadControl,picture etc. But did not find a working solution. File.Delete will gives the "File in use" Error image.save will gives the "GDI+ interface" Error which means another file with the same name is in use.

Any Help is really Appreciated

Upvotes: 0

Views: 211

Answers (1)

Chris Haas
Chris Haas

Reputation: 55457

Instead of saving the uploaded file somewhere before working on it you should be able to create your Bitmap directly from it using UploadPic.PostedFile.InputStream. You can then eliminate your File.Delete() call, too. I don't have an IDE in front of my but this should roughly work:

//Create an image from the posted file's stream
Bitmap image = new Bitmap(UploadPic.PostedFile.InputStream);
Bitmap picture = new Bitmap(ListBox1.SelectedItem.Value);
image = ResizeImage(image, picture.Width, picture.Height);
image.Save("~/Resources/" + Path.GetFileName(ListBox1.SelectedItem.Value));

Upvotes: 1

Related Questions