Miza
Miza

Reputation: 49

Retrieve image from multiple folders

How can I look for an image in multiple folders? This is my current code but it only retrieves from one folder.

string imgFilePath = @"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo\" 
                      + textBoxEmplNo.Text + ".jpg";
if (File.Exists(imgFilePath))
{
    pictureBox1.Visible = true;
    pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
    //Display message that No such image found
    pictureBox1.Visible = true;
    pictureBox1.Image = Image.FromFile(@"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo\No-image-found.jpg");
}

Upvotes: 0

Views: 1120

Answers (2)

EpicKip
EpicKip

Reputation: 4043

I changed your code just a bit to search for an image in multiple folders:

//BaseFolder that contains the multiple folders 
string baseFolder = "C:\\Users\\myName\\Desktop\\folderContainingFolders";
string[] employeeFolders = Directory.GetDirectories( baseFolder );

//Hardcoded employeeNr for test and png because I had one laying around
string imgName =  "1.png";

//Bool to see if file is found after checking all
bool fileFound = false;

foreach ( var folderName in employeeFolders )
{
    var path = Path.Combine(folderName, imgName);
    if (File.Exists(path))
    {
        pictureBox1.Visible = true;
        pictureBox1.Image = Image.FromFile(path);
        fileFound = true;
        //If you want to stop looking, break; here 
    }
}
if(!fileFound)
{
    //Display message that No such image found
    pictureBox1.Visible = true;
    pictureBox1.Image = Image.FromFile(@"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo\No-image-found.jpg");
}

Upvotes: 1

yogesh keraliya
yogesh keraliya

Reputation: 156

try code snippet given below. you can add n number of folder path to look at by just adding new entry into folder path string array.

String[] possibleFolderPaths = new String[] { "folderpath1" , "folderpath2", "folderpath3" };
        String imgExtension = ".jpg";
        Boolean fileFound = false;
        string imgFilePath = String.Empty;

        // loop through each folder path to check if file exists in it or 
not.
        foreach (String folderpath in possibleFolderPaths)
        {
            imgFilePath = String.Concat(folderpath, 
textBoxEmplNo.Text.Trim(),imgExtension);

            fileFound = File.Exists(imgFilePath);

            // break if file found.
            if (fileFound)
            {
                break;
            }

        }

        if (fileFound)
        {
            pictureBox1.Visible = true;
            pictureBox1.Image = Image.FromFile(imgFilePath);

            imgFilePath = string.Empty;
        }
        else
        {
            //Display message that No such image found
            pictureBox1.Visible = true;
            pictureBox1.Image = Image.FromFile(@"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo\No-image-found.jpg");
        }

Upvotes: 0

Related Questions