网络上居然找不到现成的代码,特此补充一篇.
关键字: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 " "+filename.Substring(i+1);
}
}