从多个文件夹中检索图像

时间:2017-05-09 07:51:12

标签: c# winforms visual-studio

如何在多个文件夹中查找图像?这是我当前的代码,但它只从一个文件夹中检索。

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");
}

2 个答案:

答案 0 :(得分:1)

我稍微更改了您的代码,以便在多个文件夹中搜索图片:

//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");
}

答案 1 :(得分:0)

尝试下面给出的代码段。您可以添加n个文件夹路径,只需在文件夹路径字符串数组中添加新条目即可查看。

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");
        }