<%@ 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>");
}
}
}