C#-基于TreeView和ListView的简易版文件管理器

TreeView

TreeView控件利用层次结构向用户展示一系列相关信息。利用TreeView控件,可以把相关信息组织成易于管理的块。

在TreeView控件中显示的每个数据项(节点)都对应于一个TreeNode对象。该对象的Nodes属性为一个集合,包含该对象下属的所有子节点。

TreeView控件中每个节点都有一个标题和两个可选图像,这两个图像分别用来图形化节点的选中或未被选中状态,使用图像需ImageList控件支持。由Windows资源管理器可知,在运行时TreeView控件的层次结构中任何节点都可以扩展或收缩显示或隐藏它的子节点。

新建节点(四种构造函数)

// Initialize a new instance of the System.Windows.Forms.TreeNode class with
// the specified label tetx
TreeNode rootNode = new TreeNode(string text);
// Initialize a new instance of the System.Windows.Forms.TreeNode class with
// the specified label tetx and the child tree nodes
TreeNode rootNode = new TreeNode(string text, TreeNode[] children);
// Intialize a new instance of the System.Windows.Forms.TreeNode class with
// the specified label text and images to display when the tree node is in  a
// selected and unselected
TreeNode rootNode = new TreeNode(string text, int ImageIndex, int selectedImageIndex);
// Initialize a new instance of the System.Windows.Forms.TreeNode class with
// the specified label text,the child tree nodes and images to display when the tree node // is in a selected and unselected
TreeNode rootNode = new TreeNode(string text, int ImageIndex, int selectedImageIndex, TreeNode[] children);

常用方法

  1. 设置节点的值
    在构造函数中string text参数是TreeNode的Text属性,也就是名字,显示在窗体上,而节点的值不会显示出来,代表这个节点存储的值,值可以是任意类型

    treenode.Tag = object;
    

    在后续也可以通过treenode.Tag的方式获取存储的数据

  2. 添加/删除子树
    通过Add和Remove方式给节点添加节点或删除节点

    treenode1.Nodes.Add(treenode2); // 把treenode2添加到treenode1的子树中
    treenode1.Nodes.Remove(treenode2);// 把treenode2从treennode1的子树中移除
    

ListView

ListView的Items Collection由许多item组成,每个item都是一行,同理Column Collection也由许多Column,每一个Column都是一列,都需要实例化后才能以Add方法添加到ListView中

对于一组item和column可以通过AddRange方法添加

需要注意的是,每构造一个item实例都要初始化第一列的值,之后可以再通过item.SubItems.Add的方法添加后续的列

Directory

Directory是目录类,可以用目录类创建、移动目录,Directory是static类,可以直接通过类名来调用方法

常用的方法如下:

方 法含 义示 例
CreateDirectory创建目录和子目录DirectoryInfodi=Directory. CreateDirectory(‘‘c:\mydir’’);
Delete删除目录及其内容Directory.Delete(‘‘c:\mydir’’);//目录必须为空
Move移动文件和目录内容Directory.Move=(‘‘c:\mydir’’, ‘‘c:\mynewdir’’);
Exists确定给定的目录字符串是否存在物理上对应的目录Directory.Exists(‘‘c:\mydir’’);
GetCurrentDirectory获取应用程序的当前工作目录console.WriteLine(''Current Directory is: ‘’+ currentPath);
SetCurrentDirectory将应用程序的当前工作目录设置为指定目录Directory. SetCurrentDirectory(''c:\ ‘’);
GetCreationTime获取目录创建的日期和时间DateTime dt = Directory.GetCreationTime (Environment.CurrentDirectory);
GetDirectories获取指定目录中子目录的名称string [] subdirectoryEntries = Directory.GetDirectories(‘‘c:\mydir’’);
GetFiles获取指定目录中文件的名称string [] files= Directory. GetFiles (‘‘c:\mydir’’);

DirectoryInfo

在使用DirectoryInfo类的属性和方法前必须先创建它的对象实例,在创建时需要指定该实例所对应的目录。例如

DirectoryInfo di=new DirectoryInfo(''c:\\mydir'');

常用的方法:

方 法含 义示 例
Create创建目录di. Create();
Delete删除DirectoryInfo实例所引用的目录及其内容di. Delete();
MoveTo将DirectoryInfo实例及其内容移到新的路径di.MoveTo(‘‘c:\Program files’’);
CreateSubDirectory创建一个或多个子目录DirectoryInfo di = di.CreateSubdirectory(“SubDir”);
GetDirectories返回当前目录的子目录DirectoryInfo[] subdirs=di. GetDirectories();
GetFiles返回当前目录的文件列表FileInfo[] files=di. GetFiles();

Directory是一个静态类,它提供了文件夹操作的一般方法,每次调用这些方法,都需要通过参数来指定当前的操作是针对那个文件夹的(功能类似于API)

DirectoryInfo类表示某一个指定的文件夹,需要在构造函数中绑定这个文件夹。它的属性与方法都是针对这个绑定的文件夹而言的。

一般而言,对于单一的操作使用Directory类更方便,针对某个特定文件夹的多项操作则使用DirectoryInfo类更方便。

基于TreeView和ListView实现的简易版文件管理器

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
        PopulateTreeView();
    }

    private void PopulateTreeView()
    {
        //TreeNode是TreeView中的节点
        TreeNode rootNode;
        string path = "C:\\Users\\22596\\Desktop\\2022Spring";
        DirectoryInfo info = new DirectoryInfo(path);
        if (info.Exists)
        {
            // TreeNode(string text)
            rootNode = new TreeNode(info.Name,0,0);
            //TreeNode.Tag是objec型变量 能接受任何数据
            rootNode.Tag = info;
            //定义了带两个参数的GetDirectories函数
            GetDirectories(info.GetDirectories(), rootNode);
            treeView1.Nodes.Add(rootNode);
        }
    }

    // 模拟生成树节点的过程-层层递推
    private void GetDirectories(DirectoryInfo[] subDirs, TreeNode nodeToAddTo)
    {
        TreeNode aNode;
        DirectoryInfo[] subsubDirs;
        foreach (DirectoryInfo subDir in subDirs)
        {
            aNode = new TreeNode(subDir.Name,0,0);
            aNode.Tag = subDir;
            subsubDirs = subDir.GetDirectories();
            // DirectoryInfo.Length表示子目录的个数
            if (subsubDirs.Length != 0)
                GetDirectories(subsubDirs, aNode);
            nodeToAddTo.Nodes.Add(aNode);
        }
    }
	
    //点击treeview上的节点时的事件相应
    private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
    {
        TreeNode newSelected = e.Node;
        listView1.Items.Clear();
        // 强制类型转换 将存储string数据的treenode.Tag强制转换成DirectoryInfo
        DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
        ListViewItem.ListViewSubItem[] subItems;
        ListViewItem item = null;

        foreach (DirectoryInfo dir in nodeDirInfo.GetDirectories())
        {
            item = new ListViewItem(dir.Name,0);
            subItems = new ListViewItem.ListViewSubItem[]
            {new ListViewItem.ListViewSubItem(item,"Directory"),
             new ListViewItem.ListViewSubItem(item,dir.LastAccessTime.ToShortDateString())};
            item.SubItems.AddRange(subItems);
            listView1.Items.Add(item);
        }

        foreach (FileInfo file in nodeDirInfo.GetFiles())
        {
            item = new ListViewItem(file.Name,1);
            subItems = new ListViewItem.ListViewSubItem[]
            {new ListViewItem.ListViewSubItem(item,"File"),
             new ListViewItem.ListViewSubItem(item,file.LastAccessTime.ToShortDateString())};
            item.SubItems.AddRange(subItems);
            listView1.Items.Add(item);
        }

        listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
    }
}
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
以下是一个简单的C# ListView案例,实现了添加、删除、编辑和保存数据的功能: ``` using System; using System.Windows.Forms; namespace ListViewExample { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnAdd_Click(object sender, EventArgs e) { ListViewItem item = new ListViewItem(txtName.Text); item.SubItems.Add(txtAge.Text); item.SubItems.Add(txtAddress.Text); lvData.Items.Add(item); } private void btnDelete_Click(object sender, EventArgs e) { foreach (ListViewItem item in lvData.SelectedItems) { lvData.Items.Remove(item); } } private void btnEdit_Click(object sender, EventArgs e) { if (lvData.SelectedItems.Count > 0) { ListViewItem item = lvData.SelectedItems[0]; item.SubItems[0].Text = txtName.Text; item.SubItems[1].Text = txtAge.Text; item.SubItems[2].Text = txtAddress.Text; } } private void btnSave_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; saveFileDialog.Title = "Save data to file"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(saveFileDialog.FileName)) { foreach (ListViewItem item in lvData.Items) { writer.WriteLine("{0}\t{1}\t{2}", item.SubItems[0].Text, item.SubItems[1].Text, item.SubItems[2].Text); } } MessageBox.Show("Data saved successfully!"); } } } } ``` 在窗体设计器中添加一个ListView控件和四个Button控件,并设置其Text属性为“Add”,“Delete”,“Edit”和“Save”。然后在窗体的代码中添加以上代码即可实现相关功能。 以下是一个简单的C# TreeView案例,实现了添加、删除和编辑节点的功能: ``` using System; using System.Windows.Forms; namespace TreeViewExample { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnAdd_Click(object sender, EventArgs e) { if (txtNode.Text.Length > 0) { if (tvData.SelectedNode == null) { tvData.Nodes.Add(txtNode.Text); } else { tvData.SelectedNode.Nodes.Add(txtNode.Text); tvData.SelectedNode.Expand(); } } } private void btnDelete_Click(object sender, EventArgs e) { if (tvData.SelectedNode != null) { tvData.SelectedNode.Remove(); } } private void btnEdit_Click(object sender, EventArgs e) { if (tvData.SelectedNode != null && txtNode.Text.Length > 0) { tvData.SelectedNode.Text = txtNode.Text; } } } } ``` 在窗体设计器中添加一个TreeView控件和三个Button控件,并设置其Text属性为“Add”,“Delete”和“Edit”。然后在窗体的代码中添加以上代码即可实现相关功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linengcs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值