我有一个树视图,我试图填充文件夹和文件。树视图填充文件夹就好了但不是文件。这是我的代码:
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的文件以及树视图中的文件夹。有人可以告诉我我做错了吗?
答案 0 :(得分:1)
问题是您的代码没有考虑文件夹层次结构的第一级:
private void PopulateTree()
{
var rootFolder = new DirectoryInfo(@"C:\inetpub\wwwroot\yourwebproject");
var root = AddNodeAndDescendents(rootFolder);
TreeView1.Nodes.Add(root);
}
private TreeNode AddNodeAndDescendents(DirectoryInfo folder)
{
var node = new TreeNode(folder.Name, folder.Name);
var subFolders = folder.GetDirectories();
foreach (DirectoryInfo subFolder in subFolders)
{
var child = AddNodeAndDescendents(subFolder);
node.ChildNodes.Add(child);
}
foreach (FileInfo file in folder.GetFiles("*.bch"))
{
var tn = new TreeNode(file.Name, file.FullName);
node.ChildNodes.Add(tn);
}
return node;
}