C# 在列表视图中显示图像
我正在用C#编写代码,将指定文件夹中未知数量的图像显示到“listview”中。我不知道如何获取该特定文件夹中的所有文件。 我知道我必须使用循环和数组,但我不知道如何使用。 下面是我用来访问“已知文件名”文件的代码。 这是一个windows窗体应用程序C# 在列表视图中显示图像,c#,listview,listviewitem,C#,Listview,Listviewitem,我正在用C#编写代码,将指定文件夹中未知数量的图像显示到“listview”中。我不知道如何获取该特定文件夹中的所有文件。 我知道我必须使用循环和数组,但我不知道如何使用。 下面是我用来访问“已知文件名”文件的代码。 这是一个windows窗体应用程序 private void btnZoom_Click(object sender, EventArgs e) { ImageList imgs = new ImageList(); imgs.ImageSize = new Siz
private void btnZoom_Click(object sender, EventArgs e)
{
ImageList imgs = new ImageList();
imgs.ImageSize = new Size(100, 100);
string[] paths = { };
paths = Directory.GetFiles("TestFolder");
try
{
foreach (string path in paths)
{
imgs.Images.Add(Image.FromFile(path));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
listView1.SmallImageList = imgs;
listView1.Items.Add("2",0);
}
要获取您可以执行的所有图像文件
IEnumerable<string> paths = Directory.GetFiles(@"Your Dir", "*.*").Where(x=>x.EndsWith(".png") || x.EndsWith(".jpg")); //add all the extensions you wish in
IEnumerable path=Directory.GetFiles(@“Your Dir”,“**”)。其中(x=>x.EndsWith(“.png”)| | x.EndsWith(“.jpg”)//在中添加您希望的所有扩展名
然后,您可以在列表中进行迭代,将它们添加到以下是工作代码: 代码是:
private void button1_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
imageList1.Images.Clear();
string[] pics = System.IO.Directory.GetFiles( "pics//");
listView1.View = View.SmallIcon;
listView1.SmallImageList = imageList1;
imageList1.ImageSize = new Size(64, 64);
foreach (string pic in pics)
{
imageList1.Images.Add(Image.FromFile(pic));
}
for (int j = 0; j < imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
listView1.Items.Add(item);
}
}
private void按钮1\u单击(对象发送者,事件参数e)
{
listView1.Items.Clear();
imageList1.Images.Clear();
字符串[]pics=System.IO.Directory.GetFiles(“pics/”);
listView1.View=View.SmallIcon;
listView1.SmallImageList=imageList1;
imageList1.ImageSize=新大小(64,64);
foreach(图片中的字符串图片)
{
imageList1.Images.Add(Image.FromFile(pic));
}
对于(int j=0;j
在designer设置时:
@Uniquedesign这将是您的新路径变量。@Uniquedesign只需替换字符串[]路径…..路径=目录。。。。对于给定的codeDone,但它在x.EndsWith(“.png”)中显示错误,错误在当前上下文中不存在,并且x=>x','expected@Uniquedesignsry有一个额外的=>在那里。应该没问题now@Uniquedesign那么,是时候进行一些调试了。首先查看图像扩展名是否为png/jpg,如果不是,请将它们添加到or语句中。然后查看paths变量是否获得了所需的所有文件路径。并检查您的代码是否适用于单个图像。文件位于文件夹中,并且该文件夹位于应用程序的调试文件夹中。我想我不需要任何路径,只需要文件夹的名称。@Uniquedesign,请查看更新的代码,我在foreach之前移动了一些行,因为设置imageList.ImageSize将清除所有图像,这使您可以加载两次图像。通过这样做,问题将得到解决。哦,好的,谢谢。它现在运行得很好。谢谢你的帮助。