0

how File.Delete() file temp.jpg with process A if locked by process B. how close handles file temp.jpg

IOExceoption: The process cannot access the file Because it is being used by another process

protected void ButtonJcrop_Click(object sender, EventArgs e)
{

    MembershipUser user = Membership.GetUser();
    String tempPath = Server.MapPath("..") + @"\Users\" + user.ProviderUserKey.ToString() + @"\temp.gif";


    System.Drawing.Image img = System.Drawing.Image.FromFile(tempPath);
    Bitmap bmpCropped = new Bitmap(100, 100);
    Graphics g = Graphics.FromImage(bmpCropped);
    Rectangle rectDestination = new Rectangle(0, 0, bmpCropped.Width, bmpCropped.Height);
    Rectangle rectCropArea = new Rectangle(Int32.Parse(hfX.Value), Int32.Parse(hfY.Value), Int32.Parse(hfWidth.Value), Int32.Parse(hfHeight.Value));
    g.DrawImage(img, rectDestination, rectCropArea, GraphicsUnit.Pixel);

    String mapPath = @"\Users\" + user.ProviderUserKey.ToString() + @"\" + user.ProviderUserKey.ToString() + ".gif";
    bmpCropped.Save(Server.MapPath("..") + mapPath);
    // bmpCropped.Save(Server.MapPath("..") + @"\Images\thumbs\CroppedImages\" + Session["WorkingImage"]);
    imCropped.ImageUrl = Request.ApplicationPath + mapPath;
    **File.Delete(tempPath);**

    PlaceHolderImCropped.Visible = true;
}
rmtheis
  • 5,992
  • 12
  • 61
  • 78
PMD
  • 46
  • 1
  • 10
  • possible duplicate of [How can I unlock a file that is locked by a process in .NET](http://stackoverflow.com/questions/242882/how-can-i-unlock-a-file-that-is-locked-by-a-process-in-net) – Ry- Apr 02 '12 at 19:00

4 Answers4

1

Wait for process B to release the resource.

Pro-tip: Process B locked the file for a reason. Stealing it is a bad idea in any situation I can think of that isn't pathological.

If you're in a pathological situation:

  1. Get out of the pathological situation. You're only digging yourself in deeper.
  2. Kill process B.

Are there other techniques? Yes. They are by definition not safe, however, so don't do that.

Greg D
  • 43,259
  • 14
  • 84
  • 117
0

File tempPath is read by

System.Drawing.Image img

So before you delete that file, just use Dispose() method.

img.Dispose();
OammieR
  • 2,800
  • 5
  • 30
  • 51
0
    Bitmap bmpCropped = new Bitmap(100, 100);
    Graphics g = Graphics.FromImage(bmpCropped);
    Rectangle rectDestination = new Rectangle(0, 0, bmpCropped.Width, bmpCropped.Height);
    Rectangle rectCropArea = new Rectangle(Int32.Parse(hfX.Value), Int32.Parse(hfY.Value), Int32.Parse(hfWidth.Value), Int32.Parse(hfHeight.Value));

using (System.Drawing.Image img = System.Drawing.Image.FromFile(tempPath)) g.DrawImage(img, rectDestination, rectCropArea, GraphicsUnit.Pixel);
PMD
  • 46
  • 1
  • 10
0

The only way is for the locking process to pass control to the next process. Then you can catch the exception or the file will be locked until the locking process dies or passes control.

Sully
  • 14,672
  • 5
  • 54
  • 79