Question

I'm loading image thumbnails into a ListView control successfully:

lsvImageThumbs.Items.Clear();
        imgl_ImageThumbs.Images.Clear();

        string[] files = Directory.GetFiles(@"C:\Documents and Settings\Etc\Desktop\Test");

        for (int indexFiles = 0; indexFiles < files.Length; indexFiles++)
        {
            Image img = Image.FromFile(files[indexFiles]);
            DirectoryInfo dinfo = new DirectoryInfo(files[indexFiles]);
            imgl_ImageThumbs.Images.Add(dinfo.Name, img);
            lsvImageThumbs.Items.Add(files[indexFiles], dinfo.Name, indexFiles);
        }

Then I can select the image thumbnails and want to Move the files to a directory:

if (dlg.ShowDialog() == DialogResult.OK)
                {
                    foreach (ListViewItem items in lsvImageThumbs.SelectedItems)
                    {
                        //File.Copy(items.Name, dlg.SelectedPath + "\\" + items.Text);
                        File.Move(items.Name, dlg.SelectedPath + "\\" + items.Text);
                        MessageBox.Show(items.Text + " Taken");
                    }
                }

File.Copy works without a problem but for File.Move I get the following error:

The process cannot access the file because it is being used by another process.
Was it helpful?

Solution

Please note that I also answered your same question on the MSDN forums as well.

Image.FromFile locks the file until the image is disposed, which is why you get the error. You can get around this by copying the file into memory and use the copy in your ImageList.

Example:

ImageList list = new ImageList();

Image diskImage = Image.FromFile("mypic.jpg");
Image memoryImage = new Bitmap(diskImage);

diskImage.Dispose(); // Releases the lock

list.Images.Add(memoryImage);

Changes to your code:

lsvImageThumbs.Items.Clear();
imgl_ImageThumbs.Images.Clear();

string[] files = Directory.GetFiles(@"C:\Documents and Settings\Etc\Desktop\Test");

for (int indexFiles = 0; indexFiles < files.Length; indexFiles++) {
    Image img = Image.FromFile(files[indexFiles]);

    // Create a copy of the image in memory
    Image memImg = new Bitmap(img);

    // Dispose of the original and release the file system lock
    img.Dispose();

    DirectoryInfo dinfo = new DirectoryInfo(files[indexFiles]);

    // Updated this line to add memImg
    imgl_ImageThumbs.Images.Add(dinfo.Name, memImg);

    lsvImageThumbs.Items.Add(files[indexFiles], dinfo.Name, indexFiles);
}

Your File.Move should now work.
Image.FromFile on MSDN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top