本文介绍了使用C#在目录中循环子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个目录'Folder',里面有很多子目录。在每个子目录中都有很多图像。我想循环遍历'Folder'目录中的子目录,然后循环遍历每个目录中的所有图像,将图像导出到Excel,以及来自1 excel工作表中每个子目录的图像。



例如如果我有10个子目录,我应该有1个excel工作簿和10个excel工作表,然后在每个excel工作表中将有来自每个子目录的图像。



这个是我尝试过但在我尝试遍历每个子目录中的图像时给出错误:

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:

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



问题:如何遍历目录中的每个子目录,然后使用每个子目录中的所有图像循环C#?



请帮帮我,谢谢。


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.

推荐答案


这篇关于使用C#在目录中循环子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:43
查看更多