2017-05-30 17 views
0

我是C#编程语言的新手。任何人都可以帮助我如何从多个文件夹检索图像在文件夹>文件夹>文件夹>图像。以下是我已经尝试的代码,但它只能检索图像,如果文件夹>图像。我有这样的尝试string baseFolder = @"\\\\egmnas01\\hr\\photo\\~";但仍然无法正常工作。请有人帮助我。谢谢。如何检索图像,如果文件夹不共享相同的基本文件夹

string baseFolder = @"\\\\egmnas01\\hr\\photo\\"; 
    string[] employeeFolders = Directory.GetDirectories(baseFolder); 

    string imgName = textBoxEmplNo.Text + ".jpg"; 
    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 (!fileFound) 
    { 

     pictureBox1.Visible = true; 
     pictureBox1.Image = Image.FromFile(@"C:\Users\jun\Desktop\images\photo\No-image-found.jpg"); 
    } 
+0

您是否想要查找名称与您在子目录树中提供的文件名相匹配的文件?如果您不知道子目录,您可能需要类似以下内容来找到匹配的文件:System.IO.Directory.GetFiles(@“c:\ test \”,“\\ *。jpg”,System .IO.SearchOption.AllDirectories);' – john

+0

@john代码替换此代码'string baseFolder = @“\\\\ egmnas01 \\ hr \\ photo \\”;'?因为我已经尝试过,但仍然无法工作。 – Miza

回答

1

我相信以下应该可以帮助您

static void Main(string[] args) 
{ 
    // test path... replace with the path you need 
    string baseFolder = @"D:\test\"; 

    string imgName = textBoxEmplNo.Text + ".jpg"; 
    bool fileFound = false; 

    DirectoryInfo di = new DirectoryInfo(baseFolder); 
    foreach (var file in di.GetFiles(imgName, SearchOption.AllDirectories)) 
    { 
     pictureBox1.Visible = true; 
     pictureBox1.Image = Image.FromFile(file.FullName); 

     fileFound = true; 
     break; 
    } 

    if (!fileFound) 
    { 

     pictureBox1.Visible = true; 
     pictureBox1.Image = Image.FromFile(@"C:\Users\jun\Desktop\images\photo\No-image-found.jpg"); 
    } 
} 

请注意,也有类似的questions已经问(回答)在这个论坛上,也许,对于不同的文件(XML而不是JPG) 还,当您第一次开始使用.Net API或者您感到困惑时,请参阅MSDN

+0

感谢您的帮助。但仍无法检索图像。 :( – Miza

+0

@Miza是否有与名称匹配的文件,但上述逻辑仍未找到它?请将'di.GetFiles(...)'检索到的所有文件名打印到控制台/消息框。如果'di.GetFiles(“*。jpg”,SearchOption.AllDriectories)'调用被创建,您是否至少会列出某些文件?您可以尝试使用类似的嵌套文件夹结构编写类似的示例并查看它的位置失败,如果它失败 – Shankar

+0

它是必要的'静态无效的主要(字符串[] args)'?因为我是'私人无效textBoxWorkNo_KeyUp(对象发件人,KeyEventArgs e)'代码' – Miza