繁体   English   中英

在C#中保存图像名称

[英]Save image name in C#

我正在尝试读取当前图像文件名或图像名称,例如0.png或1.png,但是失败。 我正在尝试以下方法。 在下面的代码中, images是一个已经包含的列表

images.Add(Image.FromFile(fileinfo.FullName));

任何建议或想法都会有所帮助。 是否可以在程序的当前位置存储文件名?

foreach (Control control in tableLayoutPanel1.Controls) // run loop untill every control inside tablelayoutpanel1.Controls is check or read
    {
        Button btns = control as Button;   // btn sotre the current button in table.contr 
        if (btns != null)                  // check btn got a button from the panel then
        {
            int randomNumber = random.Next(images.Count);   // pic the random image from list by its index which are already in images list and also count how many are they
            //MessageBox.Show(images.Count.ToString());     // if 6 images then 6 will be the max index value for 
            btns.BackgroundImage = images[randomNumber];    // change btn image to current random image
            copyImages.Add(images[randomNumber]);           // fileName.Add(** here some query for storing current image file name required**);   
            btns.BackgroundImage = null;
            images.RemoveAt(randomNumber);  // remove the current image index from list 
            //btns.Hide();
        }
    }

fileName是我创建的列表。 我只想将文件名存储在0索引上,或者可以执行类似的操作来设置图像:将图像的名称存储在Button的Tag属性中? 如果是,怎么办?

您正在为按钮分配图像,然后将其删除:

btns.BackgroundImage = images[randomNumber]; 
...
btns.BackgroundImage = null;

那是不对的。

除了Steve Wellens发现的错误之外,还有几种方法可以做到这一点。 最简单的是

使图像成为文件名的List<String> 然后在循环中调用From File

btns.Tag = images[randomnumber];
btns.BackgroundImage = ImageFromFile(images[randomNumber]);

如果您坐着不动,则需要在使用它们之前加载所有图像。 然后其他选项将是结构或类(FileName和Image),并具有它们的列表。

或者,如果文件名是唯一的,则将图像设置为Dictionary<string,Image> ,其中string是文件名,并使用它的Keys.CountKeys.ElementAt方法使循环正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM