讀取資料夾結構生成TreeView
阿新 • • 發佈:2019-01-06
<%@ Page Title="主頁" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="選擇伺服器裡面的檔案._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> <script type="text/javascript"> function postBackByObject() { var o = window.event.srcElement; if (o.tagName == "INPUT" && o.type == "checkbox") { __doPostBack("", ""); } } </script> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> 歡迎使用 ASP.NET! </h2> <p> 若要了解關於 ASP.NET 的詳細資訊,請訪問 <a href="http://www.asp.net/cn" title="ASP.NET 網站">www.asp.net/cn</a>。 </p> <p> 您還可以找到 <a href="http://go.microsoft.com/fwlink/?LinkID=152368" title="MSDN ASP.NET 文件"> MSDN 上有關 ASP.NET 的文件</a>。 </p> <asp:Button runat="server" ID="獲取檔案路徑" Text="獲取檔案路徑" OnClick="獲取檔案路徑_Click" /> <asp:TreeView ID="tvFloder" runat="server" ShowCheckBoxes="Leaf" OnTreeNodeExpanded="tvFloder_TreeNodeExpanded" OnTreeNodeCheckChanged="tvFloder_TreeNodeCheckChanged"> </asp:TreeView> </asp:Content>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Data; namespace 選擇伺服器裡面的檔案 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { tvFloder.Attributes.Add("onclick", "postBackByObject()"); } protected void tvFloder_TreeNodeExpanded(object sender, TreeNodeEventArgs e) { if (e.Node.Depth == 0) return; e.Node.ChildNodes.Clear(); GetDirectories(e.Node.Value, e.Node); } /// <summary> /// 迴圈遍歷獲得某一目錄下的所有檔案資訊 /// </summary> /// <param name="path">目錄名</param> /// <param name="tn">樹節點</param> private static void GetDirectories(string path, TreeNode tn) { if (string.IsNullOrEmpty(path)) return; if (!Directory.Exists(path)) return; string[] directories = Directory.GetFileSystemEntries(path); //先遍歷這個目錄下的資料夾 foreach (string dir in directories) { TreeNode subtn = new TreeNode(); if (File.Exists(dir)) { subtn.ShowCheckBox = true; subtn.ImageUrl = "images/file.png"; } else { subtn.ShowCheckBox = false; subtn.ImageUrl = "images/folder.png"; } subtn.Text = dir; subtn.Expanded = false; GetDirectories(dir, subtn); tn.ChildNodes.Add(subtn); } } protected void 獲取檔案路徑_Click(object sender, EventArgs e) { string path = "F:\\技術研究\\選擇伺服器裡面的檔案\\選擇伺服器裡面的檔案\\files"; TreeNode tnThird = new TreeNode(); tnThird.Text = "根節點"; tvFloder.Nodes.Add(tnThird); GetDirectories(path, tnThird); } protected void tvFloder_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e) { Response.Write("<script>alert('"+e.Node.Text+"')</script>"); } } }