Wednesday, July 24, 2013

Export and Import SharePoint Objects ( SPSite | SPWeb | SPList | SPListItem ) using C# code


Currently I’m working on creating tool which needs to export SharePoint Objects such as SPSite, SPWeb,  SPList, SPListItem from one site to another.

Solution Background

There are SPExportObject, SPExportSettings,  SPExport, SPImportSettings, SPImport classes under Microsoft.SharePoint.Deployment namesspace. You have to simply assign the needed properties and call the appropirate methods.


I will describe how to export and import a SpWeb object so that you follow the same for other sharepoint objects as well.
Export SpWeb
public void exportSpWeb(SPWeb spWeb, string fileLocation)
  SPExportObject spExportObject = new SPExportObject();
  spExportObject.Id = spWeb.ID;
  spExportObject.IncludeDescendants = SPIncludeDescendants.All;
  spExportObject.Type = SPDeploymentObjectType.Web;
  //Here if it is a "SpSite - SPDeploymentObjectType.Site",
  //"SpList - SPDeploymentObjectType.List and the same for other objects"
  SPExportSettings settings = new SPExportSettings();
  settings.SiteUrl = spWeb.Url;
  settings.ExportMethod = SPExportMethodType.ExportAll;
  settings.FileLocation = fileLocation;
  //Location where your file should be stored Eg. C:
  settings.FileCompression = true;
  settings.IncludeSecurity = SPIncludeSecurity.All;
  settings.ExcludeDependencies = true;
  settings.BaseFileName = spExportObject.Id.ToString();
  //You can give any name
  SPExport export = new SPExport(settings);
After the execution of  method, you will find a .cmp file stored in fileLocation you gave (Eg. C:) named as you gave in the line settings.BaseFileName = spExportObject.Id.ToString();.
This is the you exported and which needs to be imported into another site.
This is the way you can import this file to another site.
public void importSites(string siteUrl, string fileLocation, string fileName)
  SPImportSettings settings = new SPImportSettings();
  settings.SiteUrl = siteUrl;
  //Destination site url.
  settings.FileLocation = fileLocation;
  //Where the file stored locally.
  settings.BaseFileName =  fileName + ".cmp";
  //Name fo the file you stored lacally.
  //.cmp is the extenstion of imported file.
  settings.FileCompression = true;

  SPImport export = new SPImport(settings);
After the execution of this method your SharePoint Object will be available in destination site.


SharePoint objects can be exported and imported using the above method.
PS: When concatenating a string with another string use String.Concat() function.

No comments:

Post a Comment