Search code examples
c#imagedispose

How can I get all Files with a certain extension, without causing an IOException that tells me that the File I want to access is still in use


I have created a Folder, let's name it Input. In there I have an Input.png and a plugin.json. Now I need to get the Image so I can put it into an Object of the Class Module.

I only have the folder as a whole dynamic path, the user can decide, where to put that folder. The foldername is also changeable. The image itself has the name of the folder it is in. So as I cannot just say

string image = path.Replace("C://Test//", "") + "Input.png";

I thought the best Idea to get the picture is by looking in the folder I currently am, store every file that ends with .png in a string-array, and just use the first index, as there will be only one .png in that folder.

In the end I want to delete that Folder, and that's where I get the IOException. So I tried this:

using (string[] imageFiles = Directory.GetFiles(path, "*.png"))
{
    module.ModuleImage = Image.FromFile(imageFiles[0]);
}

But that tells me I can't do that, cause string[] is not disposable.

What can I do to close the png file when I don't need it, so I can delete the folder?


Solution

  • Your using block is referencing the wrong thing

    Image class implements IDisposable https://learn.microsoft.com/en-us/dotnet/api/system.drawing.image?view=netframework-4.8

    string[] imageFiles = Directory.GetFiles(path, "*.png")
    
     using (module.ModuleImage = Image.FromFile(imageFiles[0]))
     {
            // do your checks
     }