• 用TreeView显示某一文件夹下的所有目录和文件


    网络上居然找不到现成的代码,特此补充一篇.

    关键字:TreeView,asp.net2.0,c#,文件,目录



    public partial class Admin_FileList_Test : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!Page.IsPostBack)

            {

                TreeNode tn = new TreeNode();

                tn.Text = "根目录";

                getDirectories(Server.MapPath("../"), tn);

     

                TreeView1.Nodes.Add(tn);

            }

        }

     

        /// <summary>

        /// 循环遍历获得某一目录下的所有文件信息

        /// </summary>

        /// <param name="path">目录名</param>

        /// <param name="tn">树节点</param>

        private static void getDirectories(string path,TreeNode tn)

        {

            string[] fileNames = Directory.GetFiles(path);

            string[] directories = Directory.GetDirectories(path);

           

            //先遍历这个目录下的文件夹

            foreach (string dir in directories)

            {

                TreeNode subtn = new TreeNode();

                subtn.Text = GetShorterFileName(dir);

                subtn.ImageUrl = "~/Images/open.gif";

                subtn.Expanded = false;

                subtn.NavigateUrl = "#";

                getDirectories(dir,subtn);

                tn.ChildNodes.Add(subtn);

            }

     

            //再遍历这个目录下的文件

            foreach (string file in fileNames)

            {

                TreeNode subtn = new TreeNode();

                subtn.ImageUrl = "~/Images/file.gif";

                subtn.Text = GetShorterFileName(file);

                tn.ChildNodes.Add(subtn);

            }

        }

     

        /// <summary>

        /// 滤去文件名前面的路径

        /// </summary>

        /// <param name="filename"></param>

        /// <returns></returns>

        private static string GetShorterFileName(string filename)

        {

            return "&nbsp;"+filename.Substring(i+1);

        }

    }

  • 相关阅读:
    闭包
    正则的理解
    正则
    Date对象
    math对象
    js异步
    dom事件
    事件对象-2
    事件对象
    函数作用域
  • 原文地址:https://www.cnblogs.com/aspnetx/p/880419.html
Copyright © 2020-2023  润新知