且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从C#中的列表框中删除图像

更新时间:2023-12-05 15:32:16

如果我收到您的问题.
(我仍然不明白什么是ListBox控件的属性ItemsSource和什么是"bitmapimages")

试试这个.

If I got your question.
(I still don''t understand what is property ItemsSource for ListBox control and what is "bitmapimages")

Try this one.

if (isFirst)
{
    listBox1.DataSource = null;
    listBox1.Items.Clear();
    var imageslist = new List<string>();

    var myImagesDir = new System.IO.DirectoryInfo(@"dir path");
    foreach (System.IO.FileInfo myimagesfile
             in myImagesDir .GetFiles("*.jpg"))
    {
        imageslist.Add(myimagesfile.Name);
    }
    listBox1.DataSource = imageslist;

    isFirst = false;
}
else
{
    listBox1.DataSource = null;

    isFirst = true;
}</string>


我认为我们需要查看"..."中的内容. FileInfo对象显然没有正确清理,这很可能是因为您将对它的引用存储在列表中(不应该).这很容易做到,因为 Image.FromStream和Image.FromFile都使流保持打开状态,因此在Image对象的生存期内将文件锁定.

因此,您需要做的是打开文件,将内容读入MemoryStream,然后使用它来创建图像:
I think we need to see what is in ''...''. The FileInfo object is clearly not getting cleaned up correctly and that might well be because you are storing a reference to it in the list (which you shouldn''t). This is easy to do as both Image.FromStream and Image.FromFile keep the stream open and therefore the file locked for the lifetime of the Image object.

So what you need to do is open the file, read the contents into a MemoryStream, and use that to create your image:
foreach(FileInfo file in files){
 FileStream fs = file.OpenRead();
 MemoryStream ms = new MemoryStream();
 fs.CopyTo(ms);
 fs.Close(); // this frees the file
 
 Image image = Image.FromStream(ms); // note: NOT ''fs'' or Image.FromFile

}