Click here to Skip to main content
15,358,946 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
hi Members,

I have a directory 'Folder' with many subdirectories inside this directory. Inside every subdirectory there are many images. I want to loop through subdirectories in the 'Folder' directory, then loop through all images in every directory to export the images out to Excel, with images from each subdirectory in 1 excel worksheet.

For e.g. if I have 10 subdirectories, I should have 1 excel workbook with 10 excel worksheets, then in each excel worksheet there will be images from each subdirectory.

This is what I have tried but give me error when I tried to loop through images in each subdirectory:
C#
public void ExportToExcel()
       {
       //for export
       ExcelPackage objExcelPackage = new ExcelPackage();   //create new workbook

       string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Folder"));
       int count = 0;
       int count1=0;
       int x = 25;
       int finalValue = 0;

       foreach (string subdir in filesindirectory)
       {
           count++;
           ExcelWorksheet ws = objExcelPackage.Workbook.Worksheets.Add("Worksheet" + count); //create new worksheet

           foreach (string img in subdir)
           {
               count1++;
               System.Web.UI.WebControls.Image TEST_IMAGE = new System.Web.UI.WebControls.Image();
               System.Drawing.Image myImage = System.Drawing.Image.FromFile(img);
               var pic = ws.Drawings.AddPicture(count.ToString(), myImage);
               // Row, RowoffsetPixel, Column, ColumnOffSetPixel
               if (count1 > 1)
               {
                   pic.SetPosition(finalValue, 0, 2, 0);
                   finalValue += (x + 1); // Add 1 to have 1 row of empty row
               }
               else
               {
                   pic.SetPosition(count1, 0, 2, 0);
                   finalValue = (count1 + x) + 1; // Add 1 to have 1 row of empty
               }
           }
       }

           var filepath = new FileInfo(@"C:\Users\user\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx");
           objExcelPackage.SaveAs(filepath);
       }

Question: How to loop through each sub directories in a directory, then loop through all images from each sub directory using C#?

Please help me on this, thanks.
Posted
Comments
   
Why not reading original MSDN documentation, but a bit more thoroughly?
—SA

1 solution

First of all, look at those Directory.GetFiles methods.

It seems to be extremely simple, but there is just one subtle problem (which you may not face, if you, for example, really need all files). I explained it here: Directory.Get.Files search pattern problem[^].

—SA
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900