递归法绑定文件夹到导航树&在指定文件夹下新建文件夹
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.QueryString["listName"] != null) { BindLibConstruct(Request.QueryString["listName"]); } } } //利用递归法将指定的文档库(这里是Document Library)绑定到treeview上 public void BindLibConstruct(string listName) { SPWeb web = SPContext.Current.Web; SPList list = web.Lists[listName]; SPFolderCollection folders = list.RootFolder.SubFolders; //将文档库设为根节点(文档库本身也是一个文件夹) TreeNode rootNode = new TreeNode(); rootNode.Text = list.RootFolder.Name; rootNode.Value = list.RootFolder.UniqueId.ToString(); trvwLibConstruct.Nodes.Add(rootNode); foreach (SPFolder folder in folders) //遍历第一级的文件夹 { if (folder.Name == "Forms")//去掉默认的系统文件夹 { continue; } TreeNode parentnode = new TreeNode(); parentnode.Text = folder.Name; parentnode.Value = folder.UniqueId.ToString();//将文件夹得GUID存入到节点的value中 rootNode.ChildNodes.Add(parentnode); ChildDocFolder(folder, parentnode); //遍历第一级文件夹下的每一个文件夹 } } /// <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)// //如果不存在子文件夹就返回 { return; } else { foreach (SPFolder spfolder in folder.SubFolders) { if (spfolder.Name == "Forms")//去掉默认的系统文件夹 { continue; } TreeNode node = new TreeNode(); node.Text = spfolder.Name; node.Value = spfolder.UniqueId.ToString(); currentNode.ChildNodes.Add(node);//添加当前文件夹到TreeView中 //node.Parent.SelectAction = TreeNodeSelectAction.Expand; //设置点击节点为展开 ChildDocFolder(spfolder, node); //递归添加文件夹 } } } protected void btnNewFolder_Click(object sender, EventArgs e) { string folderText = txtNewFolder.Text; //在指定文件夹下新增一个文件夹; Guid folderGuid = Guid.Parse(trvwLibConstruct.SelectedNode.Value); SPList list = SPContext.Current.Web.Lists[Request.QueryString["listName"]]; //SPDocumentLibrary list = SPContext.Current.Web.Lists[Request.QueryString["listName"]] as SPDocumentLibrary; //在指定文件夹下新建一个文件夹。最高一级文件夹如BBSMovie无法这样取得,替代方案可以是SPContext.Current.Web.GetFolders(Guid)或者是分情况 //SPFolder parentFolder = list.GetItemByUniqueId(folderGuid).Folder; SPFolder parentFolder = list.RootFolder; if (folderGuid != list.RootFolder.UniqueId) { parentFolder = list.GetItemByUniqueId(folderGuid).Folder; } //允许创建文件夹。 list.EnableFolderCreation = true; foreach (SPFolder subFolder in parentFolder.SubFolders) { if (txtNewFolder.Text==subFolder.Name) { Response.Write("<script language='javascript'>alert('已有相同名称的文件夹存在');</script>"); return; } } //在指定文件夹下新建一个类型为文件夹名字为 txtNewFolder.Text的文件夹 SPListItem item = list.AddItem(parentFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, txtNewFolder.Text); //item["Title"] = txtNewFolder.Text; item.Update(); list.Update(); //在导航树上添加新建的文件夹节点 TreeNode node = new TreeNode(txtNewFolder.Text, item.UniqueId.ToString()); trvwLibConstruct.SelectedNode.ChildNodes.Add(node); }
效果图: