static List<Mulu> GetMuluList(string path)//获取一级目录并记录到Mulu对象中返回一个mulu类型的list反省集合 { if (Directory.Exists(path)) { List<Mulu> ltml = new List<Mulu>(); string[] arrdir = Directory.GetDirectories(path); for (int i = 0; i < arrdir.Length; i++) { Mulu newml = new Mulu() { title = System.IO.Path.GetFileName(arrdir[i]), path = arrdir[i] }; ltml.Add(newml); SetMuluChildren(newml); } return ltml; } else { return null; } } static void SetMuluChildren(Mulu ml) //递归设置每个mulu对象path目录下的子文件夹记录到children集合中 { string[] arrdir = Directory.GetDirectories(ml.path); ml.numberoffile = Directory.GetFiles(ml.path, "*", SearchOption.AllDirectories).Length; ml.title += " (" + ml.numberoffile + ")"; for (int i = 0; i < arrdir.Length; i++) { Mulu newml = new Mulu() { title = System.IO.Path.GetFileName(arrdir[i]), path = arrdir[i] }; ml.Children.Add(newml); SetMuluChildren(newml); } } public class Mulu { public string title //记录显示的标题 { get; set; } public string path //记录完整的目录 { get; set; } public int numberoffile //记录目录下所有的文件数量 包含子目录 { get; set; } public List<Mulu> Children //记录子目录 { get; set; } public Mulu() { Children = new List<Mulu>(); } }
WPF界面中TreeView
<TreeView Name="tv" Grid.Column="0" Margin="0,0,0,-0.333" TreeView.SelectedItemChanged = "tvSelect" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<Image VerticalAlignment="Center" Source="/WPF_FTP;component/Images/Dir.ico" Width="16" Height="16" Margin="2,2,2,2"></Image>
<TextBlock VerticalAlignment="Center" Text="{Binding title}"></TextBlock>
<StackPanel.ToolTip>
<TextBlock Text="{Binding numberoffile}" TextWrapping="Wrap"></TextBlock>
</StackPanel.ToolTip>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>