using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace UploadArchiveImage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
treeView1.AfterCheck += TreeView1_AfterCheck;
}
private void TreeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
this.treeView1.AfterCheck -= TreeView1_AfterCheck;
checkNode(e.Node, e.Node.Checked);
this.treeView1.AfterCheck += TreeView1_AfterCheck;
this.treeView1.ResumeLayout();
}
private void checkNode(TreeNode node, bool ischecked)
{
node.Checked = ischecked;
foreach (TreeNode c in node.Nodes)
{
checkNode(c, ischecked);
}
}
private void btnLoadTree_Click(object sender, EventArgs e)
{
if (this.txtSourceFolder.Text.Length == 0)
{
MessageBox.Show("没有选择成果文件夹路径");
return;
}
string path = this.txtSourceFolder.Text;
var files = Directory.GetFiles(path);
var folderInfo = new FolderInfo();
folderInfo.Name = Path.GetFileName(path);
foreach (string subFile in files)
{
folderInfo.Files.Add(Path.GetFileName(subFile));
}
string[] subDirs = Directory.GetDirectories(path);
foreach (string subDir in subDirs)
{
folderInfo.Folders.Add(GetFilesRecursion1(subDir));
}
//加载到树
this.treeView1.Nodes.Clear();
var root = treeView1.Nodes.Add(folderInfo.Name);
foreach (var f in folderInfo.Folders)
{
var c = root.Nodes.Add(f.Name + ((f.Folders.Count == 0) ? "(" + f.Files.Count.ToString() + ")" : ""));//加上文件个数的
LoadFoldersToTree(c, f);
}
}
private void LoadFoldersToTree(TreeNode node, FolderInfo fi)
{
foreach (var item in fi.Folders)
{
var child = node.Nodes.Add(item.Name + ((item.Folders.Count == 0)?"("+item.Files.Count.ToString()+")":""));
LoadFoldersToTree(child, item);
}
}
public FolderInfo GetFilesRecursion1(string pathname)
{
var fi = new FolderInfo();
fi.Name = Path.GetFileName(pathname);
string[] subFiles = Directory.GetFiles(pathname);
foreach (string subFile in subFiles)
{
fi.Files.Add(subFile);
}
string[] subDirs = Directory.GetDirectories(pathname);
foreach (string subDir in subDirs)
{
fi.Folders.Add(GetFilesRecursion1(subDir));
}
return fi;
}
}
public class FolderInfo
{
public string Name { get; set; }
private List<FolderInfo> _folders = new List<FolderInfo>();
public List<FolderInfo> Folders { get { return this._folders; } set { this._folders = value; } }
private List<string> _files = new List<string>();
public List<string> Files { get { return this._files; } set { this._files = value; } }
}
}