題設:
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){
}
}