遍历目录中的子目录
Loop through sub directories in directory
我有一个目录 'Folder',该目录中有许多子目录。每个子目录中都有许多图像。我想遍历 'Folder' 目录中的子目录,然后遍历每个目录中的所有图像以将图像导出到 Excel,每个子目录中的图像都在一个 Excel 工作表中。
例如如果我有十个子目录,我应该有一个 Excel 工作簿和十个 Excel 工作表,然后在每个 Excel 工作表中会有来自每个子目录的图像。
这是我尝试过的方法,但图像只出现在工作表 1 而不是所有工作表中:
public void ExportToExcel()
{
//for export
ExcelPackage objExcelPackage = new ExcelPackage(); //create new workbook
string[] filesindirectory = Directory.GetDirectories(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 Directory.GetFiles(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(count1.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# 循环遍历每个子目录中的所有图像?
这应该列出从 C:\Images 开始的所有文件,并遍历所有子目录及其子目录。
public void ExportToExcel()
{
//for export
var objExcelPackage = new ExcelPackage(); //create new workbook
this.ListFiles(objExcelPackage, 0, Server.MapPath("~/Folder"));
var filepath = new FileInfo(@"C:\Users\user\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx");
objExcelPackage.SaveAs(filepath);
}
public void ListFiles(ExcelPackage objExcelPackage, int worksheetIndex, string path)
{
var imageCount = 0;
var x = 25;
var finalValue = 0;
var files = Directory.GetFiles(path).Select(s => new FileInfo(s));
if (files.Any())
{
//create new worksheet
var ws = objExcelPackage.Workbook.Worksheets.Add("Worksheet" + (++worksheetIndex));
foreach (var file in files)
{
imageCount++;
var TEST_IMAGE = new System.Web.UI.WebControls.Image();
var myImage = System.Drawing.Image.FromFile(img);
var pic = ws.Drawings.AddPicture(imageCount.ToString(), myImage);
// Row, RowoffsetPixel, Column, ColumnOffSetPixel
if (imageCount > 1)
{
pic.SetPosition(finalValue, 0, 2, 0);
finalValue += (x + 1); // Add 1 to have 1 row of empty row
}
else
{
pic.SetPosition(imageCount, 0, 2, 0);
finalValue = (imageCount + x) + 1; // Add 1 to have 1 row of empty
}
}
}
foreach (var dir in Directory.GetDirectories(path))
{
this.ListFiles(objExcelPackage, worksheetIndex, dir);
}
}
Janne Matikainen 答案是正确的,但你需要知道如何修改你的代码...
首先更改您的代码这一行
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Folder"));
至
string[] filesindirectory = Directory.GetDirectories(Server.MapPath("~/Folder"));
其次,您需要在子文件夹路径中搜索文件,这是您的
foreach (string subdir in filesindirectory)
subdir 是您的目录路径。
只需返回与获取文件相同的操作即可
foreach (string img in Directory.GetFiles(subdir))
完成 foreach 子目录后
foreach (string img in Directory.GetFiles(subdir))
{
// Your Code
}
// Reset the Count1
count1 = 0;
重置它,因为您要增加每个 sheet 的动态行生成。
然后你在 new sheet 并且你没有重置它。
会按照之前的sheet继续计数。
要获取文件夹名称,您可以通过拆分轻松获取它。
在您创建作品之前sheet,请按照以下步骤进行操作。
string[] splitter = subdir.Split('\');
string folderName = splitter[splitter.Length - 1];
做笔记 如果 folderName 包含一些符号,它可能无法将其设置为 excel worksheet 而且名字不能太长。
请确保您替换为 excel worksheet
支持的符号
Directory.GetFiles(dir) returns dir 中的所有文件,不含文件夹
你应该使用 Directory.EnumerateDirectories(dir)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
private static void Main(string[] args)
{
try
{
string dirPath = @"\archives09\reports";
List<string> dirs = new List<string>(Directory.EnumerateDirectories(dirPath));
foreach (var dir in dirs)
{
Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\") + 1));
}
Console.WriteLine("{0} directories found.", dirs.Count);
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}
}
The Composite Pattern 符合您的问题。
public interface IExcelWorksheetAdapter
{
//todo: implement this method, here you have everything you need for an image file
void AddPicture(FileSystemItem aFile);
}
public class FileSystemItem
{
public virtual string FullPath { get; protected set; }
public virtual int Level { get; set; }
public virtual string Name
{
get
{
if (string.IsNullOrWhiteSpace(FullPath)) return string.Empty;
return FullPath.Split('\').Last();
}
}
public virtual void Operation(IExcelWorksheetAdapter ws) { }
}
public class FolderItem : FileSystemItem
{
public FolderItem(string fullPath)
{
Items = new List<FileSystemItem>();
if (!Directory.Exists(fullPath)) return;
FullPath = fullPath;
var files = Directory.GetFiles(FullPath).Select(p => new FileItem(p) { Level = this.Level + 1 }).ToList();
Items.AddRange(files);
var subFolders = Directory.GetDirectories(fullPath).Select(p => new FolderItem(p) {Level = this.Level + 1}).ToList();
Items.AddRange(subFolders);
}
public List<FileSystemItem> Items { get; set; }
public override void Operation(IExcelWorksheetAdapter ws)
{
Items.ForEach(x => x.Operation(ws));
}
}
public class FileItem : FileSystemItem
{
public FileItem(string path)
{
if (File.Exists(path))
{
FullPath = path;
}
}
public override void Operation(IExcelWorksheetAdapter ws)
{
ws.AddPicture(this);
}
}
[TestFixture]
public class DirectoryCompositeTest
{
[Test]
public void Operation_for_a_directory_files()
{
var directory = new FolderItem(AppDomain.CurrentDomain.BaseDirectory);
directory.Operation(new Sample()); // give your IExcelWorksheetAdapter implementation here.
}
}
public class Sample : IExcelWorksheetAdapter
{
public void AddPicture(FileSystemItem aFile)
{
Console.WriteLine(Indent(aFile.Level) + aFile.Name);
}
private string Indent(int level)
{
string result = "";
for (int i = 0; i < level; i++)
{
result += "-";
}
return result;
}
}
我有一个目录 'Folder',该目录中有许多子目录。每个子目录中都有许多图像。我想遍历 'Folder' 目录中的子目录,然后遍历每个目录中的所有图像以将图像导出到 Excel,每个子目录中的图像都在一个 Excel 工作表中。
例如如果我有十个子目录,我应该有一个 Excel 工作簿和十个 Excel 工作表,然后在每个 Excel 工作表中会有来自每个子目录的图像。
这是我尝试过的方法,但图像只出现在工作表 1 而不是所有工作表中:
public void ExportToExcel()
{
//for export
ExcelPackage objExcelPackage = new ExcelPackage(); //create new workbook
string[] filesindirectory = Directory.GetDirectories(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 Directory.GetFiles(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(count1.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# 循环遍历每个子目录中的所有图像?
这应该列出从 C:\Images 开始的所有文件,并遍历所有子目录及其子目录。
public void ExportToExcel()
{
//for export
var objExcelPackage = new ExcelPackage(); //create new workbook
this.ListFiles(objExcelPackage, 0, Server.MapPath("~/Folder"));
var filepath = new FileInfo(@"C:\Users\user\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx");
objExcelPackage.SaveAs(filepath);
}
public void ListFiles(ExcelPackage objExcelPackage, int worksheetIndex, string path)
{
var imageCount = 0;
var x = 25;
var finalValue = 0;
var files = Directory.GetFiles(path).Select(s => new FileInfo(s));
if (files.Any())
{
//create new worksheet
var ws = objExcelPackage.Workbook.Worksheets.Add("Worksheet" + (++worksheetIndex));
foreach (var file in files)
{
imageCount++;
var TEST_IMAGE = new System.Web.UI.WebControls.Image();
var myImage = System.Drawing.Image.FromFile(img);
var pic = ws.Drawings.AddPicture(imageCount.ToString(), myImage);
// Row, RowoffsetPixel, Column, ColumnOffSetPixel
if (imageCount > 1)
{
pic.SetPosition(finalValue, 0, 2, 0);
finalValue += (x + 1); // Add 1 to have 1 row of empty row
}
else
{
pic.SetPosition(imageCount, 0, 2, 0);
finalValue = (imageCount + x) + 1; // Add 1 to have 1 row of empty
}
}
}
foreach (var dir in Directory.GetDirectories(path))
{
this.ListFiles(objExcelPackage, worksheetIndex, dir);
}
}
Janne Matikainen 答案是正确的,但你需要知道如何修改你的代码...
首先更改您的代码这一行
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Folder"));
至
string[] filesindirectory = Directory.GetDirectories(Server.MapPath("~/Folder"));
其次,您需要在子文件夹路径中搜索文件,这是您的
foreach (string subdir in filesindirectory)
subdir 是您的目录路径。
只需返回与获取文件相同的操作即可
foreach (string img in Directory.GetFiles(subdir))
完成 foreach 子目录后
foreach (string img in Directory.GetFiles(subdir))
{
// Your Code
}
// Reset the Count1
count1 = 0;
重置它,因为您要增加每个 sheet 的动态行生成。
然后你在 new sheet 并且你没有重置它。
会按照之前的sheet继续计数。
要获取文件夹名称,您可以通过拆分轻松获取它。
在您创建作品之前sheet,请按照以下步骤进行操作。
string[] splitter = subdir.Split('\');
string folderName = splitter[splitter.Length - 1];
做笔记 如果 folderName 包含一些符号,它可能无法将其设置为 excel worksheet 而且名字不能太长。
请确保您替换为 excel worksheet
Directory.GetFiles(dir) returns dir 中的所有文件,不含文件夹 你应该使用 Directory.EnumerateDirectories(dir)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
private static void Main(string[] args)
{
try
{
string dirPath = @"\archives09\reports";
List<string> dirs = new List<string>(Directory.EnumerateDirectories(dirPath));
foreach (var dir in dirs)
{
Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\") + 1));
}
Console.WriteLine("{0} directories found.", dirs.Count);
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}
}
The Composite Pattern 符合您的问题。
public interface IExcelWorksheetAdapter
{
//todo: implement this method, here you have everything you need for an image file
void AddPicture(FileSystemItem aFile);
}
public class FileSystemItem
{
public virtual string FullPath { get; protected set; }
public virtual int Level { get; set; }
public virtual string Name
{
get
{
if (string.IsNullOrWhiteSpace(FullPath)) return string.Empty;
return FullPath.Split('\').Last();
}
}
public virtual void Operation(IExcelWorksheetAdapter ws) { }
}
public class FolderItem : FileSystemItem
{
public FolderItem(string fullPath)
{
Items = new List<FileSystemItem>();
if (!Directory.Exists(fullPath)) return;
FullPath = fullPath;
var files = Directory.GetFiles(FullPath).Select(p => new FileItem(p) { Level = this.Level + 1 }).ToList();
Items.AddRange(files);
var subFolders = Directory.GetDirectories(fullPath).Select(p => new FolderItem(p) {Level = this.Level + 1}).ToList();
Items.AddRange(subFolders);
}
public List<FileSystemItem> Items { get; set; }
public override void Operation(IExcelWorksheetAdapter ws)
{
Items.ForEach(x => x.Operation(ws));
}
}
public class FileItem : FileSystemItem
{
public FileItem(string path)
{
if (File.Exists(path))
{
FullPath = path;
}
}
public override void Operation(IExcelWorksheetAdapter ws)
{
ws.AddPicture(this);
}
}
[TestFixture]
public class DirectoryCompositeTest
{
[Test]
public void Operation_for_a_directory_files()
{
var directory = new FolderItem(AppDomain.CurrentDomain.BaseDirectory);
directory.Operation(new Sample()); // give your IExcelWorksheetAdapter implementation here.
}
}
public class Sample : IExcelWorksheetAdapter
{
public void AddPicture(FileSystemItem aFile)
{
Console.WriteLine(Indent(aFile.Level) + aFile.Name);
}
private string Indent(int level)
{
string result = "";
for (int i = 0; i < level; i++)
{
result += "-";
}
return result;
}
}