You are here: Home » Copy files in sites and site collections

Copy files in sites and site collections

Posted by jleung
No Comments »

Recently, I need to write a utility tools that handles moving documents (or aspx pages in a site) within the same site or accross site collections. The WSS 3.0 object model provides classes that would do that easily in code.

I use the methods in SPFile class to do a copy/move operation since the source and destination locations are in the same wss site.

SPSite site = new SPSite(txtWebUrl.Text);
SPWeb web = site.OpenWeb(relativeUrl);

SPFolder srcFolder = web.GetFolder(srcFolderName);
SPFileCollection collFiles = srcFolder.Files;

collFiles[index].CopyTo(destFolderName + "/" + collFiles[index].Name);

web.dispose();
site.dispose();

To copy files across site collection, I use the SPFileCollection class:

SPFileCollection targetPages = target.Files;
SPFileCollection sourcePages = source.Files; 
 foreach (SPFile page in sourcePages)
{   
      try
   
    
{
       
           
byte[] binFile = page.OpenBinary();
       
           
SPFile newPage = targetPages.Add(targetSiteUrl + "/" + page.Name, binFile);
   
     
}
   
     
catch (Exception ex)
   
    
{
            
MessageBox.Show(ex.Message);
      }
}

Your email is never shared.
Required fields are marked *




Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>