Search images across subdirectories

Asked

Viewed 62 times

0

I need to search for images in all subdirectories and present them in one picturebox, but the code I currently have only allows me to search in a single folder and without filtering by file types such as *jpg, *png, etc....

Follow my code below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace _myfotospf
{
    public partial class FormFotos1 : Form
    {
        public FormFotos1()
        {
            InitializeComponent();
        }

        private void FormFotos_Load(object sender, EventArgs e)
        {
            string[] files = Directory.GetFiles(@"C:\Users\...\Imagens");
            DataTable table = new DataTable();
            table.Columns.Add("Nome do ficheiro (duplo clique para ver a miniatura)");
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo file = new FileInfo(files[i]);
                table.Rows.Add(file.Name);
            }
            dataGridView1.DataSource = table;
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            FormFotos2 myForm = new FormFotos2();
            string imageName = dataGridView1.CurrentRow.Cells[0].Value.ToString();
            Image img;
            img = Image.FromFile(@"C:\Users\...\Imagens\" + imageName);
            myForm.pictureBox1.Image = img;
            myForm.ShowDialog();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}

2 answers

0

You can return one Ienumerable with the directories of your files. This method I am passing you will look for in the root directory and in the subdirectories from the informed path.

First parameter is the root directory you want to start searching for your files.

Second parameter is the file search pattern, in which case we are saying to fetch all files from all extensions.

Third parameter we are saying that we will search in all subdirectories from our root path.

The Where clause of Linq is for filtering the files that have the extensions we want to find, in your case you want jpg or png. If you want to insert one more extension, just add one more condition OR to the desired extent.

IEnumerable<string> arquivos = Directory.EnumerateFiles(@"C:\Imagens", "*.*", SearchOption.AllDirectories).Where(w => w.ToLower().EndsWith(".jpg") || w.ToLower().EndsWith(".png"));

0

I think this solution is quite comprehensive:

// se pretender ter várias pastas
List<string> diretorios = new List<string>()
{
    @"C:\Pasta1",
    @"C:\Pasta2",
    @"C:\Pasta3"
};

// se pretender pesquisar várias extensões
// é necessário ter um ponto antes da extensão
List<string> extensoes = new List<string>()
{
    ".jpg",
    ".bmp",
    ".png",
    ".tiff",
    ".gif"
};

private void FormFotos_Load(object sender, EventArgs e)
{
    DataTable table = new DataTable();

    table.Columns.Add("Nome do ficheiro (duplo clique para ver a miniatura)");

    foreach (string diretorio in diretorios)
    {
        var ficheiros = Directory.EnumerateFiles(diretorio, "*", SearchOption.AllDirectories).
            Where(r => extensoes.Contains(Path.GetExtension(r.ToLower())));

        foreach (var ficheiro in ficheiros)
            table.Rows.Add(Path.GetFileName(ficheiro));
    }

    dataGridView1.DataSource = table;
}
  • João Martins, Thanks. Now there are no results in datagridview

  • Okay, one "." point was missing before each extension when we declared the list extensoes. I edited the code and it should work!

  • That’s right. I didn’t even notice that detail. The problem is that the results appear in datagridview but when I double click on the table to view the images, they do not appear. Formfotos2 myForm = new Formfotos2(); string imageName = dataGridView1.CurrentRow.Cells[0].Value.Tostring(); Image img; img = Image.Fromfile(@"C:........." + imageName); myForm.pictureBox1.Image = img; myForm.Showdialog();

  • Validate if the path to the image is correct when you do the Image.FromFile.

  • When the images are in the root of the directory, they appear, but when they are inside other subfolders, it gives error: System.IO.Filenotfoundexception Hresult=0x80070002 Message=C:......... 20170301_102446.jpg

  • In the variable diretorios All you have to do is put in a directory, or it will do the same thing three times unnecessarily. As for the problem of the path, put the absolute path instead of the relative path.

  • The path is already absolute. I deleted the folder names.

  • Then there is some error in the path itself. The error is quite explicit System.IO.FileNotFoundException.

  • Images only do not appear if they are inside subfolders. I don’t know how to solve this.

  • If you place the path manually on this line Image.FromFile(@"C:\Users\...\Imagens\" + imageName);, still not working?

  • João Martins, thanks again for the help. It doesn’t work. picturebox only returns the image if it is in the root folder that I point out on the way. If the image is inside subfolders, it no longer appears. I’m turning my head and I can’t find the reason why.

  • Will it be access permissions? Already tried to access Visual Studio as Administrator?

  • Not permissions. Had already tested. The problem is that the path to the file is not correct if the image is inside another folder. Type: if image x is in folder A, it appears in picturebox, but if image y is inside folder B that is inside folder A, it is already wrong. The picturebox is not looking for the right path.

  • When you say that the path to the file is not correct when it is inside another folder, what exactly do you mean? What is the path? Can give a real example?

  • Let’s imagine that I have these files: C: Users User1 Desktop Images img001.jpg C: Users User1 Desktop Images 2018 img002.jpg The path that is set is: img = Image.Fromfile(@"C: Users User1 Desktop Images" + imageName); The img001.jpg file appears in the picturebox when I double-click on datagridview, but the img002.jpg image no longer appears (gives error), because double-clicking on datagridview always returns a path to the root folder, like: C: Users User1 Desktop Images img002.jpg

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.