题设:
1、 新建一个WINFORM程序,按照要求在任意文件夹中生成m个层级,每层n个文件夹。并在末级、索引最高的文件夹中生成一个txt文件。如下图所示(每个文件夹层级/个数相同)。
分析:本以为是简单的数据递归 for循环生成。花了十几分钟一点头绪也没有。然后就想想用数据结构。然后自己就写了一个树结构,然后完成对树的遍历就OK了;
代码:
树:
public class Tree
{
public string fileName { get; set; }
public Tree[] childTree { get; set; }
public Tree (int fileCount) {
childTree = new Tree[fileCount];
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="timer">递归次数</param>
/// <param name="subFileCount">子文件个数</param>
/// <param name="path">路径</param>
/// <param name="fatherNode">父节点名称</param>
public Tree( int timer, int subFileCount,string path,string fatherNode)
{
this.fileName = path;
int temp = 0;
string tempNode;
this.childTree = new Tree[subFileCount];
for (int i = 0; i < this.childTree.Count(); i++) {
if (timer > 0)
{
temp = timer - 1;
tempNode = fatherNode+"."+i;
this.childTree[i] = new Tree(temp, subFileCount, path + @"/" + tempNode,tempNode);
}
}
}
}
主函数:
<pre name="code" class="html"> private void btnSubmit_Click(object sender, EventArgs e)
{
//分别获取文件个数,文件名,文件深度;
int fileCount = int.Parse(this.fileCount.Text);
int subFileCount = int.Parse(this.subFileCount.Text);
string path = this.txtPath.Text;
int timer = int.Parse(this.timer.Text);
timer = timer + 1;
//遍历
for (int i = 0; i < fileCount; i++) {
Tree tree = new Tree(timer, subFileCount, path + @"/" + i, i.ToString());
CreatFile(tree, tree.fileName, timer);
}
}
创建文件夹的递归:
/// <summary>
/// 递归创建文件夹
/// </summary>
/// <param name="i">跟路径</param>
/// <param name="i">文件名</param>
/// <param name="j">文件个数</param>
/// <param name="j">递归深度</param>
public static void CreatFile(Tree tree, string path,int timer)
{
try
{
<span style="white-space:pre"> //如果递归大于0则继续创建文件夹,否则创建文件</span>
if (timer > 0)
{
timer = timer - 1;
for (int i = 0; i < tree.childTree.Count(); i++)
{
Directory.CreateDirectory(path);
CreatFile(tree.childTree[i], tree.childTree[i].fileName,timer);
}
}else
{
FileStream myFs = new FileStream(path+".txt", FileMode.Create);
StreamWriter mySw = new StreamWriter(myFs);
mySw.Close();
myFs.Close();
}
}catch(Exception ex){
}
}