wpf文件管理器代码
时间: 2023-12-12 22:00:59 浏览: 149
Wpf 文件下载代码
5星 · 资源好评率100%
WPF(Windows Presentation Foundation)是Windows平台上的一种用户界面框架,用于构建富客户端应用程序。下面是一个简单的WPF文件管理器代码示例:
```csharp
// MainWindow.xaml.cs
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
namespace FileExplorer
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadDirectory(Directory.GetDirectoryRoot(Directory.GetCurrentDirectory()));
}
private void LoadDirectory(string path)
{
try
{
DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectoryInfo[] directories = directoryInfo.GetDirectories();
FileInfo[] files = directoryInfo.GetFiles();
// 清空TreeView的节点
treeView.Items.Clear();
// 添加目录节点
foreach (DirectoryInfo directory in directories)
{
TreeViewItem directoryNode = new TreeViewItem();
directoryNode.Header = directory.Name;
directoryNode.Tag = directory.FullName;
directoryNode.Items.Add("*"); // 占位符,用于延迟加载子目录
directoryNode.Expanded += DirectoryNode_Expanded;
treeView.Items.Add(directoryNode);
}
// 添加文件节点
foreach (FileInfo file in files)
{
TreeViewItem fileNode = new TreeViewItem();
fileNode.Header = file.Name;
fileNode.Tag = file.FullName;
treeView.Items.Add(fileNode);
}
}
catch (Exception ex)
{
MessageBox.Show("加载目录失败:" + ex.Message);
}
}
private void DirectoryNode_Expanded(object sender, RoutedEventArgs e)
{
TreeViewItem directoryNode = (TreeViewItem)sender;
if (directoryNode.Items.Count == 1 && directoryNode.Items[0] is string)
{
directoryNode.Items.Clear();
try
{
DirectoryInfo directoryInfo = new DirectoryInfo((string)directoryNode.Tag);
DirectoryInfo[] directories = directoryInfo.GetDirectories();
FileInfo[] files = directoryInfo.GetFiles();
// 添加子目录节点
foreach (DirectoryInfo directory in directories)
{
TreeViewItem subDirectoryNode = new TreeViewItem();
subDirectoryNode.Header = directory.Name;
subDirectoryNode.Tag = directory.FullName;
subDirectoryNode.Items.Add("*"); // 占位符,用于延迟加载子目录
subDirectoryNode.Expanded += DirectoryNode_Expanded;
directoryNode.Items.Add(subDirectoryNode);
}
// 添加文件节点
foreach (FileInfo file in files)
{
TreeViewItem fileNode = new TreeViewItem();
fileNode.Header = file.Name;
fileNode.Tag = file.FullName;
directoryNode.Items.Add(fileNode);
}
}
catch (Exception ex)
{
MessageBox.Show("加载目录失败:" + ex.Message);
}
}
}
private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeView treeView = (TreeView)sender;
TreeViewItem selectedNode = (TreeViewItem)treeView.SelectedItem;
string filePath = (string)selectedNode.Tag;
txtPath.Text = filePath;
}
}
}
```
上述代码是一个简单的文件管理器,主要功能有:
- 展示指定路径下的目录和文件的树形结构;
- 支持展开目录节点并加载子目录的延迟加载功能;
- 在TreeView中选中节点时,在TextBox中显示该节点对应的文件路径。
希望以上代码能帮到你!如果还有其他问题,请随时提问。
阅读全文