Click here to Skip to main content
13,201,452 members (72,900 online)
Click here to Skip to main content
Add your own
alternative version


34 bookmarked
Posted 22 Jun 2009

Document Library Tree View Web Part for SharePoint

, 22 Jun 2009
Rate this:
Please Sign up or sign in to vote.
Document Library Tree View Web Part for SharePoint Server 2007.



The document libraries are one of the most popular features of SharePoint. Many companies have implemented their archives and Windows file sharing in document libraries. One useful view of directories and files in a document library is the treeview. If we show other useful information like size and number of files in each directory, it will be more useful for the users.

In this article, we will implement a treeview Web Part for the document library. Our intended features of this Web Part are:

  1. The tree view will show all files and folders of a document library.
  2. The size and number of files in each directory will be shown for users as a tool tip of each directory.
  3. User can select and change his target document library in an easy and graphical view.
  4. The files and directories will be sorted based on their name.

Installation and Usage

To install the library tree Web Part, you can run setup.bat in the command prompt on your server. To do so, use the following format:

setup.bat -install -siteurl http://testserver:8080

This will install the Web Part on your site collection. Edit a Web Part page like default.aspx. Select "Add a web part" and you can see the Library Tree Web Part on the Miscellaneous category:


Select Library Tree and press the Add button. Edit the Web Part and choose "Modify Shared Webpart". In the property pane, press the Browse button of the "Document library to view" textbox and select a document library. You can also type the name of the document library in that textbox. Click the Apply button.


How to use the source code

The source code is written in Visual Studio 2005 with the Visual Studio extension for Windows SharePoint Services version 1.1 .The project type is Web Part and the language is C#.

Design and implementation

  1. Core functionality
  2. .

    Each document library has a root folder. For retrieving files and folders in a folder and extracting the size and number of files in each folder, we will use these functions:

    1. Getting the files in a folder:
    2. public static List<FileInfo> GetFilesInFolder(SPFolder folder)
          List<FileInfo> result = new List<FileInfo>();
          FileInfo fileinfo;
          foreach (SPFile file in folder.Files)
              fileinfo = new FileInfo();
              fileinfo.Name = file.Name;
              fileinfo.Size = file.Length / 1024;
              fileinfo.URL = file.Url;
              fileinfo.IconURL = file.IconUrl;
              fileinfo.File = file;
          return result;
    3. Getting the folders in a folder:
    4. public static List<FolderInfo> GetFoldersInFolder(SPFolder folder)
          List<FolderInfo> result = new List<FolderInfo>();
          FolderInfo folderinfo;
          SPFolderCollection subFolders = folder.SubFolders;
          foreach (SPFolder subFolder in subFolders)
              folderinfo = new FolderInfo();
              folderinfo.Name = subFolder.Name;
              folderinfo.Size = GetFolderSize(subFolder) / 1024;
              folderinfo.URL = subFolder.Url;
              folderinfo.FilesNumber = GetNumberOfFilesInFolder(subFolder);
          return result;
    5. Getting the folder size:
    6. public static long GetFolderSize(SPFolder folder)
          long folderSize = 0;
          foreach (SPFile file in folder.Files)
              folderSize += file.Length;
          foreach (SPFolder subfolder in folder.SubFolders)
              folderSize += GetFolderSize(subfolder);
          return folderSize;
    7. Getting the number of files in a folder:
    8. public static int GetNumberOfFilesInFolder(SPFolder folder)
          int folderNum = 0;
          foreach (SPFile file in folder.Files)
              folderNum += 1;
          foreach (SPFolder subfolder in folder.SubFolders)
              folderNum += GetNumberOfFilesInFolder(subfolder);
          return folderNum;
  3. Populating trees.
  4. We can easily populate our tree view using the above functions. The main points are:

    1. The root folder of a document library can be retrieved:
    2. SPFolder root = doclib.RootFolder;
    3. We defined the FileInfo and FolderInfo classes for holding files and folder properties and sorting them. For each of these two, we have classes that implement the IComparer interface named FileInfoComparer and FolderInfoComparer. These classes are used for sorting the FileInfo and FolderInfo lists.
    4. //This class will store files information for use in  tree view
      public class FileInfo
          private string _Name;
          public string Name {get{return _Name;}set{_Name = value;}}
          private long _Size;
          public long Size {get{return _Size;}set{_Size = value;}}
          private string _URL;
          public string URL {get{return _URL;}set{_URL = value;}}
          private string _IconURL;
          public string IconURL {get{return _IconURL;}set{_IconURL = value;}}
          private SPFile _File;
          public SPFile File{get{return _File;}set{_File = value;}}
      //We will use this class for sorting FileInfo classes.
      public class FileInfoComparer : System.Collections.Generic.IComparer<FileInfo>      
          private SortDirection m_direction = SortDirection.Ascending;
          public FileInfoComparer()
              : base(){}
          public FileInfoComparer(SortDirection direction)
              m_direction = direction;
          int System.Collections.Generic.IComparer<FileInfo>.Compare(FileInfo x, FileInfo y)
              if (x == null && y == null)
                  return 0;
              else if (x == null && y != null)
                  return (m_direction == SortDirection.Ascending) ? -1 : 1;
              else if (x != null && y == null)
                  return (m_direction == SortDirection.Ascending) ? 1 : -1;
                      (m_direction == SortDirection.Ascending)
                          ? x.Name.CompareTo(y.Name)
                          : y.Name.CompareTo(x.Name);
      public class FolderInfo
          private string _Name;
          public string Name{get{return _Name;}set{_Name = value;}}
          private long _Size;
          public long Size{get{return _Size;}set{_Size = value;}}
          private string _URL;
          public string URL{get{return _URL;}set{_URL = value;}}
          private long _FilesNumber;
          public long FilesNumber{get{return _FilesNumber;}set{_FilesNumber = value;}}
      public class FolderInfoComparer : System.Collections.Generic.IComparer<FolderInfo>
          private SortDirection m_direction = SortDirection.Ascending;
          public FolderInfoComparer()
              : base(){}
          public FolderInfoComparer(SortDirection direction)
              m_direction = direction;
          int System.Collections.Generic.IComparer<FolderInfo>.Compare(FolderInfo x, FolderInfo y)
              if (x == null && y == null)
                  return 0;
              else if (x == null && y != null)
                  return (m_direction == SortDirection.Ascending) ? -1 : 1;
              else if (x != null && y == null)
                  return (m_direction == SortDirection.Ascending) ? 1 : -1;
                      (m_direction == SortDirection.Ascending)
                          ? x.Name.CompareTo(y.Name)
                          : y.Name.CompareTo(x.Name);
    5. We have a recursive function for defining nodes of our tree based on the core functionalities.
    6. public static TreeNode GetFolderNode(TreeNode node, SPFolder folder, string baseURL)
          List<FolderInfo> folders = GetFoldersInFolder(folder);
          folders.Sort(new FolderInfoComparer(SortDirection.Ascending));
          TreeNode folderNode;
          for (int j = 0; j <= folders.Count - 1; j++)
              folderNode = new TreeNode();
              folderNode.NavigateUrl = baseURL + "/" + folders[j].URL;
              folderNode.ImageUrl = baseURL + "/_layouts/images/folder.gif";
              folderNode.Text = folders[j].Name;
              folderNode.ToolTip = "Size:" + folders[j].Size.ToString() + " KBs " + 
                                   " Files:" + folders[j].FilesNumber.ToString();
              SPFolder subfolder = folder.SubFolders[folders[j].URL];
              folderNode.ChildNodes.Add(GetFolderNode(folderNode, subfolder, baseURL));
          TreeNode fileNode;
          List<FileInfo> files = GetFilesInFolder(folder);
          files.Sort(new FileInfoComparer(SortDirection.Ascending));
          for (int i = 0; i <= files.Count - 1; i++)
              fileNode = new TreeNode();
              fileNode.ImageUrl = baseURL + "/_layouts/images/" + files[i].IconURL;
              fileNode.NavigateUrl = baseURL + "/" + files[i].URL;
              fileNode.Text = files[i].Name;
              fileNode.ToolTip = "Size:" + files[i].Size + " KBs ";
          return node;
    7. The CreateChildControls() method of the Web Part calls the functions and renders the interface.
    8. protected override void CreateChildControls()
          SPWeb wb = SPContext.Current.Web;
          string baseURL = wb.Url.ToString();
          string _CorrectedLibraryPath;
              if (_LibraryPath == "")
                  throw new Exception("No Document Library selected. " + 
                        "Please select one from web part properties pane.");
              //check if the library name was selected from picker or entered manually
              if (_LibraryPath.Substring(0, 1) == "/")
                  _CorrectedLibraryPath = _LibraryPath.Substring(1);
                  _CorrectedLibraryPath = _LibraryPath;
              SPDocumentLibrary doclib = (SPDocumentLibrary)wb.Lists[_CorrectedLibraryPath];
              // A table for layout 
              Table tbl;
              TableRow row;
              TableCell cell;
              tbl = new Table();
              row = new TableRow();
              cell = new TableCell();
              // first row for title
              cell.VerticalAlign = VerticalAlign.Middle;
              cell.HorizontalAlign = HorizontalAlign.Left;
              Label lblTitle = new Label();
              lblTitle.Text = "Tree View of " + doclib.Title +":" ;
              //second row for treeview
              row = new TableRow();
              cell = new TableCell();
              cell.VerticalAlign = VerticalAlign.Middle;
              cell.HorizontalAlign = HorizontalAlign.Left;
              TreeView TreeView1 = new TreeView();                
              SPFolder root = doclib.RootFolder;
              TreeNode node = new TreeNode();
              node = Utility.GetFolderNode(node, root, baseURL);
              node.Text = doclib.Title;
              node.NavigateUrl = doclib.DefaultViewUrl;
              long size = Utility.GetFolderSize(root) / 1024;
              long numFiles = Utility.GetNumberOfFilesInFolder(root);
              node.ToolTip = "Size:" + size.ToString() + " KBs " + 
                             " Files:" + numFiles.ToString();
              node.ImageUrl = baseURL + "/_layouts/images/folder.gif";
              TreeView1.ShowLines = true;
              TreeView1.EnableViewState = false;
              //add table to webpart
          catch (Exception ex)
              Label errorLabel = new Label();
              string errorType = ex.GetType().Name;
              string errorMessage="";
              if (errorType == "InvalidCastException")
                  errorMessage = "Error: Please select a document library for tree view.";
              if (errorType == "ArgumentException")
                  errorMessage = "Error: There is no such document " + 
                                 "library with this name: " + _LibraryPath;
              errorLabel.Text = errorMessage;
    9. For selecting the target document library, we use a customized property and a custom pane for the list picker which is a feature of MOSS 2007. The source code and the method of implementation is the work of Ton Stegeman from "Selecting a SharePoint list in a webpart toolpart".
    10. In brief, we can use PickerTreeDialog.js for selecting a site or list name for a Web Part property. You can see further details in his post.

Further improvements

  1. Give the user an option to sort files and directories based on other properties such as size or date of modification.
  2. Populating the tree may take more time for bigger document libraries. We can populate the tree view on demand. This means that nodes will not be populated until the user expands that node.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Nioosha Kashani
Software Developer (Senior) AIRIC
Iran (Islamic Republic of) Iran (Islamic Republic of)
MCP (Microsoft Certified Professional)
Senior Software Developer in AIRIC (Automotive Design and Research Company).
Capabilities and interests:
.NET Framework, ASP.NET, Windows Application, Windows Workflow Foundation, SharePoint Customization and Development,SQL Server, NHibernate, BPMN and UML.
Master of Industrial Engieering from Poly-Technic of Tehran

You may also be interested in...


Comments and Discussions

QuestionProblem running setup.bat Pin
Member 1281494725-Oct-16 9:01
memberMember 1281494725-Oct-16 9:01 
Questionpopulate the tree view on demand Pin
Hardy719-Oct-16 0:12
memberHardy719-Oct-16 0:12 
QuestionAdapted for SP2013 Pin
dylan cristy9-Mar-16 6:13
memberdylan cristy9-Mar-16 6:13 
QuestionMany Thanks Pin
gudimanojreddy22-Jul-15 19:30
membergudimanojreddy22-Jul-15 19:30 
QuestionThisis another apprach Pin
Kamalnath9825-Mar-15 12:10
memberKamalnath9825-Mar-15 12:10 
QuestionFolder items needs to be collapsed when the page loads Pin
cutekoti25-May-14 22:27
membercutekoti25-May-14 22:27 
QuestionProblem Pin
Kathy Street18-Sep-13 4:45
memberKathy Street18-Sep-13 4:45 
AnswerRe: Problem Pin
Member 99188448-Nov-13 10:38
memberMember 99188448-Nov-13 10:38 
GeneralThanks! Pin
Member 1006534120-May-13 21:57
memberMember 1006534120-May-13 21:57 
QuestionDesperately need this, but Visual Studio says it's incompatible Pin
gberisha11-May-13 3:42
membergberisha11-May-13 3:42 
Generalhi Pin
Member 99661944-Apr-13 18:58
memberMember 99661944-Apr-13 18:58 
QuestionHow to enable the connection in this webpart Pin
Ashok Kumar Sah30-Oct-12 4:13
memberAshok Kumar Sah30-Oct-12 4:13 
QuestionTree view Alignment disoriented Pin
Member 87836173-Apr-12 5:02
memberMember 87836173-Apr-12 5:02 
Questiondoes this webpart work under 365 sharepoint online? Pin
joelu9-Jan-12 19:08
memberjoelu9-Jan-12 19:08 
QuestionLibrary selection Pin
saed saif7-Dec-11 22:51
membersaed saif7-Dec-11 22:51 
Questiongreat webpart but can we hide forms and take care of permissions Pin
anant846-Sep-11 17:26
memberanant846-Sep-11 17:26 
AnswerRe: great webpart but can we hide forms and take care of permissions Pin
wilkiyoshi28-May-12 9:03
memberwilkiyoshi28-May-12 9:03 
Generalsort files and directories based on other properties Pin
doni dan9-Jun-11 12:57
memberdoni dan9-Jun-11 12:57 
GeneralWebpart refresh Pin
Member 783189725-Apr-11 9:47
memberMember 783189725-Apr-11 9:47 
After I changed the ducument library name in web part edit mode, I clicked 'APPLY', the tree view can not be refreshed. if I refresh the URL, everything is fine. Please help me. Thanks.
GeneralTree View Folder navigation Pin
Subasri2914-Mar-11 19:38
memberSubasri2914-Mar-11 19:38 
QuestionWill this work with SP2010? Pin
PragneshMPatel21-Feb-11 23:58
memberPragneshMPatel21-Feb-11 23:58 
AnswerRe: Will this work with SP2010? Pin
Member 819739429-Aug-11 5:07
memberMember 819739429-Aug-11 5:07 
AnswerRe: Will this work with SP2010? Pin
DenisFratman26-Oct-11 2:10
memberDenisFratman26-Oct-11 2:10 
AnswerRe: Will this work with SP2010? Pin
zerotoon9-Aug-12 22:34
memberzerotoon9-Aug-12 22:34 
AnswerRe: Will this work with SP2010? Pin
Jonathan Pollard30-Jan-13 17:47
memberJonathan Pollard30-Jan-13 17:47 
AnswerRe: Will this work with SP2010? Pin
Member 920654317-Mar-13 15:01
memberMember 920654317-Mar-13 15:01 
GeneralMy vote of 5 Pin
sachinarpita197817-Feb-11 18:09
membersachinarpita197817-Feb-11 18:09 
GeneralProblems with Source in VS 2010 Pin
kylejg5-Jan-11 11:05
memberkylejg5-Jan-11 11:05 
Questiontree view in quick launch Pin
venkat29721-Dec-10 1:54
membervenkat29721-Dec-10 1:54 
GeneralMy vote of 4 Pin
venkat29721-Dec-10 1:50
membervenkat29721-Dec-10 1:50 
GeneralDisplay one folder in document library and its subfolders Pin
arisaron28-Oct-10 9:59
memberarisaron28-Oct-10 9:59 
GeneralRe: Display one folder in document library and its subfolders Pin
cutekoti25-May-14 22:25
membercutekoti25-May-14 22:25 
QuestionOnce code change is made how do I update webpart? Pin
arisaron28-Oct-10 9:45
memberarisaron28-Oct-10 9:45 
QuestionCan we get a build without "Forms" included? Pin
Hoopster29-Jul-10 4:11
memberHoopster29-Jul-10 4:11 
AnswerRe: Can we get a build without "Forms" included? Pin
MarkJHumphreys23-Jan-13 1:52
memberMarkJHumphreys23-Jan-13 1:52 
GeneralWant to get rid of Form folder in Tree view web part Pin
priyankasa8-Apr-10 11:51
memberpriyankasa8-Apr-10 11:51 
GeneralRe: Want to get rid of Form folder in Tree view web part Pin
steveo423-Feb-14 23:39
membersteveo423-Feb-14 23:39 
QuestionCannot Display folder in tree view Pin
mmufid1-Mar-10 19:31
membermmufid1-Mar-10 19:31 
AnswerRe: Cannot Display folder in tree view Pin
dmddgl0119-Mar-10 0:43
memberdmddgl0119-Mar-10 0:43 
GeneralRe: Cannot Display folder in tree view Pin
priyankasa8-Apr-10 6:17
memberpriyankasa8-Apr-10 6:17 
GeneralRe: Cannot Display folder in tree view Pin
remoman29-Aug-10 3:13
memberremoman29-Aug-10 3:13 
GeneralCan't get "forms" to not display Pin
milo1453-Feb-10 8:50
membermilo1453-Feb-10 8:50 
GeneralRe: Can't get "forms" to not display Pin
Tanmay Bari23-Mar-10 4:33
memberTanmay Bari23-Mar-10 4:33 
Generalthe right cell showing contents show folders that user hasnt permission Pin
donpeyote22-Jan-10 1:31
memberdonpeyote22-Jan-10 1:31 
GeneralCompiling Source Code Pin
awaites18-Dec-09 13:42
memberawaites18-Dec-09 13:42 
Generaldirection Pin
Coward24-Nov-09 23:25
memberCoward24-Nov-09 23:25 
GeneralProblem with the web part Pin
EugenioMorini2-Nov-09 5:56
memberEugenioMorini2-Nov-09 5:56 
GeneralRe: Problem with the web part Pin
Diane Burns10-Dec-09 1:19
memberDiane Burns10-Dec-09 1:19 
GeneralRe: Problem with the web part Pin
xfilesit10-Dec-09 4:08
memberxfilesit10-Dec-09 4:08 
GeneralRe: Problem with the web part Pin
julianokz217-Dec-09 4:34
memberjulianokz217-Dec-09 4:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171020.1 | Last Updated 22 Jun 2009
Article Copyright 2009 by Nioosha Kashani
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid