使用Windows Form 制作一个简易资源管理器

自制一个简易资源管理器----TreeView控件

  第一步、新建project,进行基本设置;(Set as StartUp Project;View/Toolbox/TreeView)

  使用Windows Form 制作一个简易资源管理器

第二步、开始添加节点

  添加命名空间using System.IO;    

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO; namespace _ResouceManager_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
//这里是资源管理器的根路径
string strRoot = @"H:\自制资源管理器";//路径
CreateParent(strRoot);
} private void CreateParent(string strRoot)
{
//创建根节点parent
TreeNode parent = new TreeNode();
DirectoryInfo di=new DirectoryInfo(strRoot);
parent.Text= di.Name ;
parent.Tag = di.FullName; //添加父节点
tvResouceManager.Nodes.Add(parent); //创建子节点
CreateChild(strRoot,parent);
//展开所有节点
parent.ExpandAll(); } private void CreateChild(string path,TreeNode parent )
{
DirectoryInfo di = new DirectoryInfo(path);
//所有的子文件夹
DirectoryInfo[] dirs = di.GetDirectories();
//遍历子文件夹
foreach(DirectoryInfo dir in dirs)
{
//创建子节点
TreeNode child = new TreeNode();
child.Text = dir.Name;
//child.Tag = dir.FullName; //添加子节点
parent.Nodes.Add(child); //递归实现多级文件夹的遍历、创建子节点、添加子节点
CreateChild(dir.FullName,child); //添加文件节点
CreateFile(dir.FullName,child);
}
} private void CreateFile(string p, TreeNode child)
{
DirectoryInfo di = new DirectoryInfo(p);
//路径下的所有文件
FileInfo[] files = di.GetFiles();
//添加路径下的所有文件
foreach(FileInfo file in files)
{
//创建节点
TreeNode tn = new TreeNode();
tn.Text = file.Name;
// tn.Tag = file.FullName; //添加节点
child.Nodes.Add(tn);
}
} }
}

 使用Windows Form 制作一个简易资源管理器

  这里基本上完成了目录添加,尚不能增加文件、删除文件、移动文件等操作,还需继续努力。

  右边是两个文本框,可以进行文本的编辑等(代码不全)。

  首先在左边的treeview中点击某个节点,进行判断点击的是哪个节点,如果是.doc或者是.txt就可以编辑(其他文件类型如PDF之类可以自己写代码哦)。

  先将上述代码中关于.Tag的注释取消

  

   private void tvResouceManager_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node.Tag == null) return;
string path = e.Node.Tag.ToString();
if(path.LastIndexOf(".doc")>)
{
//如果点击的是.doc文档,将标题写入上文本框
txtTitle.Text = Path.GetFileNameWithoutExtension(e.Node.Text);
//文档内容写入下文本框,并使用指定的编码规则进行读文本操作
//txtContent.Text = File.ReadAllText(path,Encoding.GetEncoding("utf-8"));
txtContent.Text = File.ReadAllText(path, Encoding.Default);
} } private void btnSave_Click(object sender, EventArgs e)
{
if (tvResouceManager.SelectedNode == null) return;
if (tvResouceManager.SelectedNode.Tag == null) return; string path = tvResouceManager.SelectedNode.Tag.ToString(); if (path.LastIndexOf(".doc") > )
{
string content = txtContent.Text;
File.WriteAllText(path, content, Encoding.Default); MessageBox.Show("Save Successed"); }
}

  

上一篇:智能硬件开发如何选择低功耗MCU


下一篇:maven 禁止连接外网仓库