I am developing a console application which will get all the files in a document library and copy it to a particular location on system. I was successful in retrieving all the files within the library. However , i am unable to retain the folder structure. Files in diff folder are place in the library without the original structure i.e all in one place. Below is the code:

if ((list.GetType().ToString()=="Microsoft.SharePoint.SPDocumentLibrary") && !list.Hidden)
                        var Listdir = Sitedir+@"\"+list.Title.ToString();

                        if (!Directory.Exists(Listdir))

                        foreach (SPListItem item in list.Items)

                            byte[] binFile = item.File.OpenBinary();

                            System.IO.FileStream fstream =

                            System.IO.File.Create(Listdir+"\\" + item.File.Name);

                            fstream.Write(binFile, 0, binFile.Length);


Is there any way to retain folder structure?




Traversing SharePoint List Folder Hierarchies

From above URL:

// Within some method somewhere
foreach(SPList list in web.Lists)
    if(list.BaseType == SPBaseType.DocumentLibrary)
        //Traverse the folder

TraverseFolder might be implemented something like this:

public long TraverseFolder(SPFolder folder)
    // Do something interesting on the folder
    // Perhaps sum up the file sizes

    long lFolderSize = 0;
        foreach (SPFile file in folder.Files)
            lFolderSize += file.Length;

        if (bRecurseFolders)
            foreach (SPFolder subfolder in folder.SubFolders)
                lFolderSize += TraverseFolder(subfolder);
    catch (Exception e)
    return lFolderSize;

I always use this for referencing, I hope this helps!

  • Superb.Thanks a lot for this.Approach in this is entirely different :). Using this, i got the desired result. The only problem is that its including hidden folders too i.e "Forms", "FormServerTemplates" etc. – Thomas Mathew Nov 27 '12 at 13:22
  • @ThomasMathew for that there are alternatives as suggested here: Checking Programatically, if Document Library Folder is Hidden.. Please mark the answer as correct if that helped! – Arsalan Adam Khatri Nov 27 '12 at 13:28
  • I had tried that. But it wont work. Also, checking property count as 21 would not work too. Anyway, i have marked the answer as correct. – Thomas Mathew Nov 27 '12 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.