0

我正在成功地将图像缩略图加载到 ListView 控件中:

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);
        }

然后我可以选择图像缩略图并希望将文件移动到目录:

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 工作没有问题,但对于 File.Move 我收到以下错误:

The process cannot access the file because it is being used by another process.
4

1 回答 1

1

请注意,我也在 MSDN 论坛上回答了您同样的问题。

Image.FromFile 锁定文件,直到图像被释放,这就是您收到错误的原因。您可以通过将文件复制到内存中并在 ImageList 中使用副本来解决此问题。

例子:

ImageList list = new ImageList();

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

diskImage.Dispose(); // Releases the lock

list.Images.Add(memoryImage);

更改您的代码:

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);
}

您的 File.Move 现在应该可以工作了。
MSDN 上的 Image.FromFile

于 2012-04-12T08:25:06.463 回答