本文介绍了c#中的TreeView控件逻辑问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
如果我选择一个以Tree结构化格式显示所有子文件夹的文件夹。但是,这里我有一个条件,即如果我选择一个文件夹,它应该显示所有子文件夹,其名称以树结构格式的_(下划线)开头。如果任何文件夹名称没有以_(下划线)启动,那么该文件夹不应该显示在树结构中。
我写了如下代码:
Hello all,
If i select one folder that displays all the sub-folders in Tree structured format. But, here i have one condition i.e If i select one folder that should display all the sub-folders which is having the name started with "_"(underscrore) in Tree structure format. If any folder name is not started with "_" (underscrore) that folder should not displayed in the Tree structure.
I have written the code like below:
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 tree_browse
{
public partial class Form1 : Form
{
string strSearchPath = string.Empty;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
folderBrowserDialog.SelectedPath = strSearchPath;
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
Properties.Settings.Default.Save();
strSearchPath = folderBrowserDialog.SelectedPath;
GetTree(strSearchPath);
}
}
void GetTree(string strSearchPath)
{
treeView1.Nodes.Clear();
SetNode(treeView1, strSearchPath);
treeView1.TopNode.Expand();
}
void SetNode(TreeView treeName, string path)
{
DirectoryInfo dirInfo = new DirectoryInfo(path);
TreeNode node = new TreeNode(dirInfo.Name);
node.Tag = dirInfo;
GetFolders(dirInfo, node);
GetFiles(dirInfo, node);
treeName.Nodes.Add(node);
}
void GetFolders(DirectoryInfo d, TreeNode node)
{
try
{
DirectoryInfo[] dInfo = d.GetDirectories();
if (dInfo.Length > 0)
{
TreeNode treeNode = new TreeNode();
foreach (DirectoryInfo driSub in dInfo)
{
treeNode = node.Nodes.Add(driSub.Name, driSub.Name, 0, 0);
GetFiles(driSub, treeNode);
GetFolders(driSub, treeNode);
}
}
}
catch (Exception ex) { }
}
void GetFiles(DirectoryInfo d, TreeNode node)
{
//if you want to search .doc or docx file then:
// var files = d.GetFiles("*.doc*");
var files = d.GetFiles("*.*");
FileInfo[] subfileInfo = files.ToArray<FileInfo>();
if (subfileInfo.Length > 0)
{
for (int j = 0; j < subfileInfo.Length; j++)
{
//Checking for Hiddend files
bool isHidden = ((File.GetAttributes(subfileInfo[j].FullName) & FileAttributes.Hidden) == FileAttributes.Hidden);
if (!isHidden)
{
TreeNode treeNode = new TreeNode();
string path = subfileInfo[j].FullName;
string name = subfileInfo[j].Name;
treeNode = node.Nodes.Add(path, name);
}
}
}
}
}
}
请更正此代码。帮帮我....
先谢谢
Please correct this code. Help me....
Thanks in Advance
推荐答案
这篇关于c#中的TreeView控件逻辑问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!