gpt4 book ai didi

c# - 在 ASP.NET C# 中使用文件填充 TreeView

转载 作者:行者123 更新时间:2023-11-30 12:44:03 24 4
gpt4 key购买 nike

我有一个 TreeView ,我正在尝试用文件夹和文件填充它。 TreeView 很好地填充了文件夹,但没有填充文件。这是我的代码:

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;
}

这是我的树的样子:

My Tree View: without files

这是文件夹中文件的图片:

My files

我只是想在 TreeView 中显示类型为 .bch 的文件以及文件夹。有人可以告诉我我做错了什么吗?

最佳答案

问题是您的代码没有考虑文件夹层次结构的第一级:

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;
}

关于c# - 在 ASP.NET C# 中使用文件填充 TreeView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29548356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com