WPF TreeView遍历硬盘
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView Name="treeFileSystem" TreeViewItem.Expanded="treeFileSystem_Expanded_1">
</TreeView>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TreeFileSystem
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
TreeViewItem item = new TreeViewItem();
item.Tag = drive;
item.Header = drive.ToString();
item.Items.Add("*");
treeFileSystem.Items.Add(item);
}
}
private void treeFileSystem_Expanded_1(object sender, RoutedEventArgs e)
{
TreeViewItem item = (TreeViewItem)e.OriginalSource;
item.Items.Clear();
DirectoryInfo dir;
if (item.Tag is DriveInfo)
{
DriveInfo drive = (DriveInfo)item.Tag;
dir = drive.RootDirectory;
}
else
{
dir = (DirectoryInfo)item.Tag;
}
try
{
foreach (DirectoryInfo subDir in dir.GetDirectories())
{
TreeViewItem newItem = new TreeViewItem();
newItem.Tag = subDir;
newItem.Header = subDir.ToString();
newItem.Items.Add("*");
item.Items.Add(newItem);
}
}
catch
{
}
}
}
}