У меня есть дерево, которое я пытаюсь заполнить папками и файлами. Древовидное представление заполняет папки просто отлично, но не файлы. Вот мой код:Заполнение древовидной структуры файлами в ASP.NET C#
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;
}
Вот что мое дерево выглядит следующим образом:
Вот картинка из файлов в папке:
I Я пытаюсь просто показать файлы с типом .bch вместе с папками в моем древовидной структуре. Может кто-нибудь, пожалуйста, скажите мне, что я делаю неправильно?
Ваш Substring болит мой мозг. Знаете ли вы, что FileInfo имеет свойство Extension? – Biscuits
@ Печенье Нет, я не знал, что – nate
Хорошо. Тем не менее, я бы предпочел использовать перегрузку GetFiles в DirectoryInfo, которая позволяет вам заранее указать шаблон поиска. – Biscuits