Populating a treeview with files in ASP.NET C# -
i have treeview trying populate folders , files. treeview populating folders fine not files. here code:
protected void page_load(object sender, eventargs e) { if (!ispostback) { populatetree(); } } private void populatetree() { //populate tree based on subfolders of specified virtualimageroot var rootfolder = new directoryinfo(virtualimageroot); var root = addnodeanddescendents(rootfolder, null); //add root treeview treeview1.nodes.add(root); } private treenode addnodeanddescendents(directoryinfo folder, treenode parentnode) { //add treenode, displaying folder's name , storing full path folder value... string virtualfolderpath; if (parentnode == null) { virtualfolderpath = virtualimageroot; } else { virtualfolderpath = parentnode.value + folder.name + "/"; } var node = new treenode(folder.name, virtualfolderpath); //recurse through 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 new treenode return node; }
here tree looks like:
here picture of files in folder:
i trying show files type .bch, along folders in treeview. can please tell me doing wrong?
the problem code didn't take account first level of folder hierarchy:
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; }