'Moving file selected in listview to another folder with button

I've got problem with moving selected file in listview using button to another folder, my code:

public void button2_Click(object sender, EventArgs e)
    {
        string[] files = Directory.GetFiles(@"C:\Users\Mkzz\Desktop\doki");
        string destinyFodler = @"C:\Users\Mkzz\Desktop\doki\test1\*.tif";
        listView1.Dispose();
        foreach (string file in files)
        {
            File.Move(file, destinyFodler);
        }
    }

It gives me error „The process cannot access the file because it is being used by another process.”. Files loaded to listview are .tif ' s images, they are also loaded into picturebox.

Is there any way to fix this?



Solution 1:[1]

Try loading the PictureBox controls using a clone image e.g.

public class ImageHelpers
{
    public static Image LoadImageClone(string Path)
    {
        Bitmap imageClone = null; 
        var imageOriginal = Image.FromFile(Path);

        imageClone = new Bitmap(imageOriginal.Width, imageOriginal.Height); // create clone, initially empty, same size

        using (var gr = Graphics.FromImage(imageClone))
        {
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            gr.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighSpeed;
            gr.DrawImage(imageOriginal, 0, 0, imageOriginal.Width, imageOriginal.Height); //copy original image onto this surface           
        }

        imageOriginal.Dispose();

        return imageClone; 
    }
}

Test we can delete the image after assigning the image to a PictureBox

private void LoadImageButton_Click(object sender, EventArgs e)
{
    pictureBox1.Image = ImageHelpers.LoadImageClone("Folders.png");
    File.Delete("Folders.png");
}

Note I'm not the author of this code, picked the code up many years ago.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1