2017-05-09 54 views
0

如何在多個文件夾中查找圖像?這是我目前的代碼,但它只能從一個文件夾中檢索。從多個文件夾中檢索圖像

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

檢索怎麼樣?從1個文本框?隨機?只需選擇一條路徑?你必須解釋你的問題 – EpicKip

+0

http://stackoverflow.com/questions/11628021/c-sharp-how-to-customize-openfiledialog-to-select-multiple-folders-and-files –

+0

@EpicKip是的,搜索圖像從1文本框。從該文本框中,它檢查圖像所具有的文件,然後在圖像框處顯示圖像。 – Miza

回答

0

我改變你的代碼只是有點搜索多個文件夾中的圖像:

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

謝謝。這行得通!你讓我的一天! :) – Miza

+0

@Miza沒問題,很高興我可以幫到 – EpicKip

+0

你介意我問問題嗎?我如何從一個文件夾中檢索多個文件夾?這意味着** string [] employeeFolders = {「folderNameA」,「folderNameB」,「folderNameC」}; **是不需要的。因爲我不想在添加文件夾時再次調整代碼。謝謝 – Miza

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"); 
     } 
相關問題