Using Treeview to display a directory structure

本文介绍了一个使用 ASP.NET 和 C# 编写的简单应用,该应用能够递归地读取服务器上的目录结构,并将其展示为树形视图。通过 TreeNode 对象实现了文件夹及其子文件夹和文件的展示。

OK, I post the code directly with no unnecessary words:

ContractedBlock.gifExpandedBlockStart.gifCode
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    
protected void Page_Load(object sender, EventArgs e)
    {
        
if (Page.IsPostBack == false)
        {
            System.IO.DirectoryInfo RootDir 
= new System.IO.DirectoryInfo(Server.MapPath("~/"));

            
// output the directory into a node
            TreeNode RootNode = OutputDirectory(RootDir, null);

            
// add the output to the tree
            TreeView1.Nodes.Add(RootNode);
        }
    }

    TreeNode OutputDirectory(System.IO.DirectoryInfo directory, TreeNode parentNode)
    {
        
// validate param
        if (directory == nullreturn null;

        
// create a node for this directory
        TreeNode DirNode = new TreeNode(directory.Name);

        
// get subdirectories of the current directory
        System.IO.DirectoryInfo[] SubDirectories = directory.GetDirectories();

        
// output each subdirectory
        for (int DirectoryCount = 0; DirectoryCount < SubDirectories.Length; DirectoryCount++)
        {
            OutputDirectory(SubDirectories[DirectoryCount], DirNode);
        }

        
// output the current directories files
        System.IO.FileInfo[] Files = directory.GetFiles();

        
for (int FileCount = 0; FileCount < Files.Length; FileCount++)
        {
            DirNode.ChildNodes.Add(
new TreeNode(Files[FileCount].Name));
        }

        
// if the parent node is null, return this node
        
// otherwise add this node to the parent and return the parent
        if (parentNode == null)
        {
            
return DirNode;
        }
        
else
        {
            parentNode.ChildNodes.Add(DirNode);
            
return parentNode;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>Using Treeview to display a directory structure</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:TreeView ID="TreeView1" runat="server">
        
</asp:TreeView>
    
</div>
    
</form>
</body>
</html>

转载于:https://www.cnblogs.com/OceanChen/archive/2009/01/28/1381210.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值