如何在文本框中获取图像文件名?

时间:2012-03-10 14:03:29

标签: c# file directory fileinfo imagelist

我有关于C#文件名的问题。我用PictureBox显示一些图片。另外我想在TextBox中写出图片的名称。我搜索fileinfo,directoryinfo,但它不起作用。

List<Image> images = new List<Image>();
 images.Add(Properties.Resources.baseball_bat);
 images.Add(Properties.Resources.bracelet);
 images.Add(Properties.Resources.bride);

pictureBox1.Image = images[..];

我想在TextBox中写下baseball_bat,新娘,手镯等。我能做什么?任何报价?

3 个答案:

答案 0 :(得分:1)

嗯,最简单的方法之一就是在List<KeyValuePair<string,Image>>IDictionary<string,image>中保存名称和图片。

以下是使用IDictionary<string,image>的示例 (由于索引,我决定SortedList<>):

var images = new SortedList<string, Image>();
images.Add("baseball_bat", Properties.Resources.baseball_bat);
images.Add("bracelet", Properties.Resources.bracelet);
...

// when you show the first image...
pictureBox1.Image = images.Values[0];
textBox1.Text = images.Keys[0];

// when you show the nth image...
pictureBox1.Image = images.Values[n];
textBox1.Text = images.Keys[n];

对于List<KeyValuePair<string,Image>>,将是:

var images = new List<KeyValuePair<string, Image>>();
images.Add(new KeyValuePair<string,Image>("baseball_bat", Properties.Resources.baseball_bat));
images.Add(new KeyValuePair<string,Image>("bracelet", Properties.Resources.bracelet));
...

// when you show the first image...
pictureBox1.Image = images[0].Values;
textBox1.Text = images[0].Keys;

// when you show the nth image...
pictureBox1.Image = images[n].Values;
textBox1.Text = images[n].Keys;

答案 1 :(得分:0)

您可以使用反射获取所有资源及其密钥(资源名称):

//a helper dictionary if you want to save the images and their names for later use
var namesAndImages = new Dictionary<String, Image>();

var resourcesSet = Properties.Resources.ResourceManager.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, true, true);

        foreach (System.Collections.DictionaryEntry myResource in resourcesSet)
        {
            if (myResource.Value is Image) //is this resource is associated with an image
            {
                String resName = myResource.Key.ToString(); //get resource's name
                Image resImage = myResource.Value as Image; //get the Image itself

                namesAndImages.Add(resName, resImage);
            }
        }

        //now you can use the values saved in the dictionary and easily get their names
        ...

更新:我已更新代码以将值保存在字典中,以便日后方便地使用它们。

答案 2 :(得分:0)

此功能已内置于...

图像列表以您可以按名称引用它们的方式存储它们的图像并返回图像。

单次使用:

private string GetImageName(ImageList imglist, int index)
    {
        return imglist.Images.Keys[index].ToString();
    }

这将返回传递索引的图像名称

以后存储值:

private Dictionary<int, string> GetImageNames(ImageList imglist)
    {
        var dict = new Dictionary<int, string>();
        int salt = 0;

        foreach (var item in imglist.Images.Keys)
        {
            dict.Add(salt, item.ToString());
            salt++;
        }
        return dict;
    }

这将返回一个字典,该字典将图片索引引用到图像列表中的字符串名称。

这是内置的,没有必要尝试扩展功能。对它...