-1

I'm using a C# application that take a file from a path as an image:

Image.FromFile(path);

and then display it in my listview.

I have then a button that calls a method to replace this image wich is selected in the listview by another image, using this method:

public void Replace(string newImgPath)
{
    if (GetImageFromPath(newImgPath) != null && GetImageFromPath(PathName) != null)
    {
        var Oldimg = GetImageFromPath(PathName);
        var NewImg = GetImageFromPath(newImgPath);

        if (NewImg.Height != Oldimg.Height)
        {
            NewImg = ResizeMe(NewImg, Oldimg.Height, Oldimg.Width);
        }

        if (File.Exists(PathName))
        {
            File.Delete(PathName);
        }

        NewImg.Save(PathName);
    }
}

But i get an exception that i cannot delete this file!

Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • 1
    What does `GetImageFromPath` do? Can you show that method? – Rufus L Aug 05 '17 at 01:12
  • @RufusL Hello sir this method basically return an Image class from a path – aurelia Lo bianco Aug 05 '17 at 01:16
  • I'm asking because the code you're showing shouldn't cause that error, so it could be from one of the methods you're calling. I assume your method does something more than `Image.FromFile(path)`, right? Please update the question with which line is throwing the exception, and what the exact exception message is. – Rufus L Aug 05 '17 at 01:18
  • the exception is `The process cannot access the file 'C:\Users\....' because it is being used by another process.` – aurelia Lo bianco Aug 05 '17 at 01:21
  • `But i get an exception that i cannot delete this file!` Please point us to the exact line that throws that exception. And the **type** of the exception.Also, let us know the exact value of `PathName`. – mjwills Aug 05 '17 at 01:23
  • @mjwills the exception is `The process cannot access the file 'C:\Users\....' because it is being used by another process.` – aurelia Lo bianco Aug 05 '17 at 01:34

1 Answers1

0

The problem is your images are not disposed properly.

I would do something like:

    Image tempImage;
    using(var oldImg = Image.FromFile(PathName))
    {
       tempImage = oldImage;
    }
    if (File.Exists(PathName))
    {
        File.Delete(PathName);
    }
DontThinkJustGo
  • 380
  • 2
  • 11