说明:涉及到知识点:TreeView控件,递归调用,

1 先把架子搭起来

步步为营-16-资料管理器步步为营-16-资料管理器
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 资料管理
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //1获取文件路径
            string path = @"E:\Java开发实战经典";
            //2加载文件目录
            LoadFileName(path, TV.Nodes);
        }

        private void LoadFileName(string path,TreeNodeCollection tn)
        {
            //3根据传来的路径获取文件夹名--此时获取的是路径全名
            string[] directories = Directory.GetDirectories(path);
            //4 获取文件名
            string[] files = Directory.GetFiles(path);

            TreeNode tc;
            foreach (string item in directories)
            {
                //5获取文件夹名
                string directoriesNames = Path.GetFileName(item);
                tc= tn.Add(directoriesNames);
                LoadFileName(item,tc.Nodes);
            }
            foreach (string item in files)
            {
                //6获取文件名
                string fileNames = Path.GetFileName(item);
                tc=tn.Add(fileNames);
            }
        }
    }
}
View Code

步步为营-16-资料管理器

2 当点击某个文件时,对文件进行操作

步步为营-16-资料管理器步步为营-16-资料管理器
  private void TVNodeClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //如果点击文件夹,是没有效果的
            if (TV.SelectedNode.Tag!=null)
            {
                string filePath = TV.SelectedNode.Tag.ToString();
                textBox1.Text = File.ReadAllText(filePath, Encoding.Default);
            }
        } 
View Code

步步为营-16-资料管理器

3 进一步对文件进行修改

步步为营-16-资料管理器步步为营-16-资料管理器
        private void btnSave_Click(object sender, EventArgs e)
        {
            string filePath = TV.SelectedNode.Tag.ToString();
            string fileType = Path.GetExtension(filePath);
            if (!fileType.Contains("txt"))
            {
                MessageBox.Show("只能修改txt文本文件");
            }
            else
            {
                File.WriteAllText(filePath, textBox1.Text, Encoding.UTF8);
                MessageBox.Show("文件修改成功!");
            }

        } 
View Code

步步为营-16-资料管理器

相关文章:

  • 2021-07-24
  • 2021-04-20
  • 2021-08-16
  • 2021-11-27
  • 2022-01-17
  • 2021-04-04
  • 2021-10-03
  • 2021-04-19
猜你喜欢
  • 2021-11-30
  • 2021-12-24
  • 2021-05-24
  • 2021-04-04
  • 2021-10-28
  • 2021-10-20
相关资源
相似解决方案