winform中获取指定文件夹下的所有图片

  • 2022-07-23 08:33:50

方法一:

c#的io自带了一个方法
directoryinfo dir = new directoryinfo("文件夹名称");
dir.getfiles();//这个方法返回值就是fileinfo类型的数组

再将获取的图片一一存入list数组中,需要从list中找即可

public string exepath = application.startuppath;

//绝对路径
directoryinfo dir = new directoryinfo("c:\\test");
//相对路径,和程序exe同目录下
//directoryinfo dir = new directoryinfo(@"test"); fileinfo[] fileinfo = dir.getfiles(); list<string> filenames = new list<string>(); foreach (fileinfo item in fileinfo) { filenames.add(item.name); }

//图片展示
 for (int i = 0; i < filenames.count; i++)
{
    string filename = filenames[i];
    this.panelautographpic.controls.add(new picturebox
    {
      backcolor = system.drawing.color.transparent,
      backgroundimagelayout = imagelayout.stretch,
      width = 300,
      height = 200,
    backgroundimage = image.fromfile(exepath + "../test/" + filename)
    });
}

方法二:

将获取的图片一一存入listbox中,需要从listbox中找即可

listbox listbox1 = new listbox();
private void get_folder(string filepath)
{
  if (directory.exists(filepath))
     {
           foreach (string d in directory.getfilesystementries(filepath))
           {
              image img = image.fromfile(d);
                if (file.exists(d) && img.rawformat.equals(system.drawing.imaging.imageformat.jpeg) || 
                        img.rawformat.equals(system.drawing.imaging.imageformat.gif) || 
                        img.rawformat.equals(system.drawing.imaging.imageformat.bmp) || 
                        img.rawformat.equals(system.drawing.imaging.imageformat.png))
                    {
                        listbox1.items.add(d.tostring());
                    }
            }
       }
       else
       {
            messagebox.show("文件夹不存在!");
       }
}
//调用
get_folder(@"指定文件夹名");

 

猜你喜欢