可视化webpart基础开发——TreeView控件读取文档库中的所有文件夹和文件(递归方法读取)
分类: SharePoint2011-12-23 14:44 1584人阅读 评论(0) 收藏 举报
可视化webpart基础开发——TreeView控件读取文档库中的所有文件夹和文件(递归方法读取)
1、在部署的sharepoint网站中新建一个名为“测试文档库”的文档库,并添加各级的子文件夹和子文件,用于测试
2、在VS2010中新建空白sharepoint项目
3、创建可视化web部件
在TreeViewTestUserControl.ascx中添加TreeView控件,ID为“TreeView1”
在TreeViewTestUserControl.ascx.cs源文件夹添加如下实现代码
全部代码:
[csharp] view plaincopy
- using System;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- //加入引用
- using Microsoft.SharePoint;
- namespace TreeViewProject.TreeViewTest
- {
- public partial class TreeViewTestUserControl : UserControl
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindDoclib();
- }
- }
- /// <summary>
- /// 绑定文档库
- /// </summary>
- private void BindDoclib()
- {
- string url = SPContext.Current.Web.Url;
- #region
- SPSecurity.RunWithElevatedPrivileges(delegate()
- {
- using (SPSite site = new SPSite(url))
- {
- using (SPWeb web = site.OpenWeb())
- {
- foreach (SPList list in web.Lists)
- {
- if (list.BaseTemplate != SPListTemplateType.DocumentLibrary)//找到文档库
- {
- continue;
- }
- else
- {
- if (list.Title == "测试文档库")
- {
- TreeNode node = new TreeNode();
- node.Text = list.Title;
- node.NavigateUrl = list.DefaultViewUrl;
- TreeView1.Nodes.Add(node);
- ChildDocFolder(list.RootFolder, node);
- }
- }
- }
- }
- }
- });
- #endregion
- }
- /// <summary>
- /// 递归方法读取文档库
- /// </summary>
- /// <param name="folder">父文件夹</param>
- /// <param name="currentNode">当前节点</param>
- private void ChildDocFolder(SPFolder folder, TreeNode currentNode)
- {
- string url = SPContext.Current.Web.Url;
- if (folder.SubFolders.Count == 0)// //如果不存在子文件夹就返回,并把文件夹中的文件加到TreeView中
- {
- foreach (SPFile file in folder.Files)//显示子文件
- {
- TreeNode node = new TreeNode();
- node.Text = file.Name;
- node.NavigateUrl = url + "/" + file.Url;
- node.ImageUrl = "_layouts/images/" + file.IconUrl;
- currentNode.ChildNodes.Add(node);
- }
- return;
- }
- else
- {
- foreach (SPFile file in folder.Files)//添加当前文件夹中的文件到TreeView中
- {
- TreeNode node = new TreeNode();
- node.Text = file.Name;
- node.NavigateUrl = url + "/" + file.Url;
- node.ImageUrl = "_layouts/images/" + file.IconUrl;
- currentNode.ChildNodes.Add(node);
- }
- foreach (SPFolder spfolder in folder.SubFolders)
- {
- if (spfolder.Name == "Forms")//去掉默认的系统文件夹
- {
- continue;
- }
- TreeNode node = new TreeNode();
- node.Text = spfolder.Name;
- node.NavigateUrl = url + "/" + spfolder.Url;
- node.ImageUrl ="_layouts/images/folder.gif";
- currentNode.ChildNodes.Add(node); //添加当前文件夹到TreeView中
- ChildDocFolder(spfolder, node); //展示当前文件夹下面的文件和文件夹
- }
- }
- }
- }
- }
代码完成,点击测试部署webpart到sharepoint网站中,在页面插入webpart,测试效果如下
时间: 2024-11-29 01:02:01