Question

I am trying to download everything (documents, lists, folders) of a web and its sub-webs and its sub-webs (if exists) and so on, I can do it for a single web but its not working for subwebs in it, code is given below,

   private void downloadList(SPObjectData objectData)
    {
        using (SPWeb currentWeb = objectData.Web)
        {
            foreach (SPList list in currentWeb.Lists)
            {
                    foreach (SPFolder oFolder in list.Folders)
                    {
                        if (oFolder != null)
                        {
                            foreach (SPFile file in oFolder.files)
                            {
                                if (CreateDirectoryStructure(tbDirectory.Text, file.Url))
                                {
                                    var filepath = System.IO.Path.Combine(tbDirectory.Text, file.Url);
                                    byte[] binFile = file.OpenBinary();
                                    System.IO.FileStream fstream = System.IO.File.Create(filepath);
                                    fstream.Write(binFile, 0, binFile.Length);
                                    fstream.Close();
                                }
                            }
                        }
                }
            }
        }
    }
Was it helpful?

Solution

That is because you want to do it recursively for the subwebs

foreach(SPWeb oWeb in currentWeb.Webs){

downloadList(oWeb); //use same logic you used above to get all the stuff from the sub web

}

So, it would be like this for your recursive method:

//notice I overloaded
private void downloadList(SPWeb oWeb){
//get subwebs of subwebs
foreach(SPWeb oWeb in currentWeb.Webs){

   downloadList(oWeb); 

}
foreach (SPList list in oWeb.Lists)
            {
                    foreach (SPFolder oFolder in list.Folders)
                    {
                        if (oFolder != null)
                        {
                            foreach (SPFile file in oFolder.files)
                            {
                                if (CreateDirectoryStructure(tbDirectory.Text, file.Url))
                                {
                                    var filepath = System.IO.Path.Combine(tbDirectory.Text, file.Url);
                                    byte[] binFile = file.OpenBinary();
                                    System.IO.FileStream fstream = System.IO.File.Create(filepath);
                                    fstream.Write(binFile, 0, binFile.Length);
                                    fstream.Close();
                                }
                            }
                        }
                }
            }
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top