Microsoft Premier Field Engineer - SharePoint

All posts are provided "AS IS" with no warranties, and confers no rights.

Code snippet to copy documents from one document library to another

Code snippet to copy documents from one document library to another

  • Comments 1
   1:  using (SPSite site = new SPSite("http://ms10:200/sites/200"))
   2:              {
   3:                  using (SPWeb web = site.OpenWeb())
   4:                  {
   5:                      SPList lib1 = (SPDocumentLibrary)web.Lists["Documents"];
   6:                      SPList lib2 = (SPDocumentLibrary)web.Lists["Site Collection Documents"];
   7:                      byte[] fileBytes = null;
   8:                      string destUrl = null;
   9:                      SPFile destFile = null;
  10:                      foreach (SPListItem item1 in lib1.Items)
  11:                      {
  12:                          fileBytes = item1.File.OpenBinary();
  13:                          destUrl = lib2.RootFolder.Url + "/" + item1.File.Name;
  14:                          destFile = lib2.RootFolder.Files.Add(destUrl, fileBytes, true /*overwrite*/);
  15:   
  16:                          fileBytes = null;
  17:                          destUrl = null;
  18:                          destFile = null;
  19:                      }
  20:   
  21:                      lib1 = null;
  22:                      lib2 = null;
  23:                  }
  24:              }
  25:              MessageBox.Show("Done!");

:: Please note that I would have just uploaded my initial code and you might want to consider proper optimization of the code and disposal of objects properly. I might not have updated the latest code here.

Comments
Page 1 of 1 (1 items)
Leave a Comment
  • Please add 6 and 5 and type the answer here:
  • Post