我的要求是枚举所有目录和特定的.tif文件(位于结构的末尾)。样品是
A (path selected from UI) <has>
B<has> and C<has>
D <has> E F G H I J
K L<has>
1.tif 2.tif
在上面的目录中,A有B和C.命名为客户端。 B有D,E,F(标注日期),D有K和L(系列)。 因此,您需要帮助检索txt或excel文件中的目录结构
B D
K 0
L 2 (since there are two tif files)
E
F
与c和其他目录类似。
答案 0 :(得分:0)
我不确定我理解你想要什么,但这里有一些让你入门的东西
private static void ProcessFolder(string folder, string level, string separator, StreamWriter output)
{
var dirs = Directory.GetDirectories(folder);
foreach ( var d in dirs )
{
output.Write(level);
output.WriteLine(d);
ProcessFolder(d, level + separator, separator, output);
}
Console.WriteLine();
var files = Directory.GetFiles(folder);
foreach ( var f in files )
{
output.Write(level);
output.WriteLine(f);
}
}
您必须自定义它以过滤TIFF或您想要的任何内容。您可以像这样调用此函数,它将生成文件
using ( var output = new StreamWriter(@"C:\test.csv") )
{
ProcessFolder(@"c:\Program files", "", ";", output);
}
双击生成的文件,Excel可能会打开:)
答案 1 :(得分:0)
也许这会成功(或至少给出一个好的起点):
public void OutputStructureToFile(string outputFileName, string folder, string searchPattern)
{
using (var file = new StreamWriter(outputFileName))
{
file.Write(GetStructure(new DirectoryInfo(folder), searchPattern));
}
}
public string GetStructure(DirectoryInfo directoryInfo, string searchPattern)
{
return GetStructureRecursive(directoryInfo, searchPattern, 0);
}
private string GetStructureRecursive(DirectoryInfo directoryInfo, string searchPattern, int level)
{
var sb = new StringBuilder();
var indentation = level * 5;
sb.Append(new String(' ', indentation));
sb.AppendLine(directoryInfo.Name);
foreach (var directory in directoryInfo.GetDirectories())
{
sb.Append(GetStructureRecursive(directory, searchPattern, level+1));
}
var groupedByExtension = directoryInfo.GetFiles(searchPattern)
.GroupBy(file => file.Extension)
.Select(group => new { Group = group.Key, Count = group.Count() });
foreach (var entry in groupedByExtension)
{
sb.Append(new String(' ', indentation));
sb.AppendLine(String.Format(" {0,10} {1,3}", entry.Group, entry.Count));
}
return sb.ToString();
}
如果你需要Excel作为.csv文件,你应该使用这个递归函数
private string GetStructureRecursiveForCsv(DirectoryInfo directoryInfo, string searchPattern, int level)
{
var sb = new StringBuilder();
var indentation = level;
sb.Append(new String(';', indentation));
sb.AppendLine(directoryInfo.Name);
foreach (var directory in directoryInfo.GetDirectories())
{
sb.Append(GetStructureRecursiveForCsv(directory, searchPattern, level+1));
}
var groupedByExtension = directoryInfo.GetFiles(searchPattern)
.GroupBy(file => file.Extension)
.Select(group => new { Group = group.Key, Count = group.Count() });
foreach (var entry in groupedByExtension)
{
sb.Append(new String(';', indentation));
sb.AppendLine(String.Format(";{0};{1}", entry.Group, entry.Count));
}
return sb.ToString();
}