【发布时间】:2015-04-09 20:28:50
【问题描述】:
我有一个试图用文件夹和文件填充的树视图。树视图正在填充文件夹,但不是文件。这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateTree();
}
}
private void PopulateTree()
{
//Populate the tree based on the subfolders of the specified VirtualImageRoot
var rootFolder = new DirectoryInfo(VirtualImageRoot);
var root = AddNodeAndDescendents(rootFolder, null);
//Add the root to the TreeView
TreeView1.Nodes.Add(root);
}
private TreeNode AddNodeAndDescendents(DirectoryInfo folder, TreeNode parentNode)
{
//Add the TreeNode, displaying the folder's name and storing the full path to the folder as the value...
string virtualFolderPath;
if (parentNode == null)
{
virtualFolderPath = VirtualImageRoot;
}
else
{
virtualFolderPath = parentNode.Value + folder.Name + "/";
}
var node = new TreeNode(folder.Name, virtualFolderPath);
//Recurse through this folder's subfolders
var subFolders = folder.GetDirectories();
foreach (DirectoryInfo subFolder in subFolders)
{
var child = AddNodeAndDescendents(subFolder, node);
foreach (FileInfo file in subFolder.GetFiles())
{
var index = file.FullName.LastIndexOf(@"\", StringComparison.Ordinal);
var strname = file.FullName.Substring(index + 1);
var name = strname.Split('.');
var tn = new TreeNode();
if (name.Length > 1 && name[1].ToLower() == "bch")
{
tn = new TreeNode(name[0], file.FullName);
}
else
{
tn = new TreeNode(name[0], file.FullName);
}
child.ChildNodes.Add(tn);
}
node.ChildNodes.Add(child);
}
//Return the new TreeNode
return node;
}
这是我的树的样子:
这是文件夹中文件的图片:
我只想显示类型为 .bch 的文件以及树视图中的文件夹。有人可以告诉我我做错了什么吗?
【问题讨论】:
-
你的子字符串伤害了我的大脑。你知道 FileInfo 有一个 Extension 属性吗?
-
@Biscuits 不,我不知道
-
好的。不过,我会选择在 DirectoryInfo 上使用 GetFiles 重载,它允许您预先指定搜索模式。
-
@Biscuits 你能给我一个代码示例吗?
-
foreach(subFolder.GetFiles("*.bch") 中的 FileInfo 文件)
标签: c# asp.net treeview treenode directoryinfo