winform中获取指定文件夹下的所有图片
方法一:
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(@"指定文件夹名");