6

I've been looking for method of copying a file or folder from one document library to a number of other libraries with the same name in each subsite for a particular site collection. What needs to happen is when a folder or file is added on one site it needs to be copied to all other sites in the collection.

I've seen that the SPFile class has a CopyTo() function but most of the answers regarding copying files I have come across suggest using

    byte[] fileBytes = item1.File.OpenBinary();
    string destUrl = lib2.RootFolder.Url + "/" + item1.File.Name;
    SPFile destFile = lib2.RootFolder.Files.Add(destUrl, fileBytes, true);

Which is the correct method for copying a file or folder structure within a site collection?

Regards ~Donald

10

SharePoint has great built in methods to copy or move documents across sub-sites or lists within the same site collection. You can use SPFile.MoveTo or SPFile.CopyTo. You can even move whole folders and their contents with the SPFolder.MoveTo method. Very nice. Unfortunately, these do not work across site collections.

where as use of RootFolder.Files.Add is something like below:

 using (SPSite site = new SPSite("http://yoursiteurl"))
        {
            using (SPWeb web = site.OpenWeb())
            {

                using (FileStream fs = (new FileInfo("c:\\somepath")).OpenRead())
                {
                    SPList list = web.Lists["test"];

                    //add metadata
                    Hashtable ht = new Hashtable();
                    ht.Add("testcol", "myfile");
                    ht.Add("vti_title", "mytitle");

                    SPFile destfile = list.RootFolder.Files.Add(strDocName, fs, ht, true);

                }


            }

        }
  • So basically you're saying for my example above CopyTo is perfectly acceptable however if I were using multiple site collections then the byte streaming method is preferable. – Donald Dunlop Sep 30 '13 at 11:09
  • Yes, exactly for your requirement you are good to go with CopyTo. – Anuja Sep 30 '13 at 11:15

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.