Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have a class that I've been working on to allow me to move items in SharePoint, whilst retaining meta data. The class is as follows:

public class Lists
    {
        /// <summary>
        /// Access and modify items in SharePoint lists within the same site
        /// </summary>
        /// <param name="siteURL"></param>
        /// <param name="sourceList"></param>
        /// <param name="destinationList"></param>
        /// <param name="retainMeta"></param>
        public static void MoveListItems(string siteURL, string sourceList, string destinationList, bool retainMeta)
        {
                Console.WriteLine("[{0}] Opening site: {1}", DateTime.Now.ToShortTimeString(), siteURL);

            using (var site = new SPSite(siteURL))
            {
                Console.WriteLine("[{0}] Opened site: {1}", DateTime.Now.ToShortTimeString(), siteURL);

                using (var web = site.OpenWeb())
                {
                    Console.WriteLine("[{0}] Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(), web.ServerRelativeUrl);

                    try
                    {
                        // Get your source and destination libraries
                        var source = web.GetList(web.ServerRelativeUrl + sourceList);
                        var destination = web.GetList(web.ServerRelativeUrl + destinationList);

                        Console.WriteLine("[{0}] Source set to: {1}", DateTime.Now.ToShortTimeString(), source);
                        Console.WriteLine("[{0}] Destination set to: {1}", DateTime.Now.ToShortTimeString(), destination);

                        // Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset
                        SPListItemCollection items = source.Items;

                        // Get the root folder of the destination we'll use this to add the files
                        SPFolder folder = web.GetFolder(destination.RootFolder.Url);

                        Console.WriteLine("[{0}] Moving {1} files from {2} to {3} - please wait...", DateTime.Now.ToShortTimeString(),
                                          items.Count, source, destination);

                        var fileCount = 0;
                        // Now to move the files and the metadata
                        foreach (SPListItem item in items)
                        {
                            //Get the file associated with the item
                            SPFile file = item.File;

                            // Create a new file in the destination library with the same properties
                            SPFile newFile = folder.Files.Add(folder.Url + "/" + file.Name, file.OpenBinary(), file.Properties, true);

                            // Optionally copy across the created/modified metadata                        
                            if (retainMeta)
                            {
                                SPListItem newItem = newFile.Item;
                                WriteFileMetaData(item, newItem);
                            }

                            // Delete the original version of the file
                            // todo: make local backup before deleting?
                            file.Delete();

                            fileCount++;
                        }
                        Console.WriteLine("[{0}] Completed moving {1} files to {2}", DateTime.Now.ToShortTimeString(), fileCount,
                                          destination);

                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        Console.WriteLine(
                            "[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.",
                            DateTime.Now.ToShortTimeString());

                        throw;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("[{0}] Exception: {1}", DateTime.Now.ToShortTimeString(), ex);

                        throw;
                    }
                }
            }
        }

        /// <summary>
        /// Access and modify items in SharePoint lists in differing sites
        /// </summary>
        /// <param name="sourceSiteURL"></param>
        /// <param name="sourceList"></param>
        /// <param name="destinationSiteURL"></param>
        /// <param name="destinationList"></param>
        /// <param name="retainMeta"></param>
        public static void MoveListItemsSiteToSite(string sourceSiteURL, string sourceList, string destinationSiteURL,
                                                   string destinationList, bool retainMeta)
        {
            Console.WriteLine("[{0}] Opening Source site: {1}", DateTime.Now.ToShortTimeString(), sourceSiteURL);

            using (var sourceSite = new SPSite(sourceSiteURL))
            {
                Console.WriteLine("[{0}] Opened Source site: {1}", DateTime.Now.ToShortTimeString(), sourceSiteURL);

                using (var sourceWeb = sourceSite.OpenWeb())
                {
                    Console.WriteLine("[{0}] Source Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(), sourceWeb.ServerRelativeUrl);

                    try
                    {
                        // Get your source library
                        var source = sourceWeb.GetList(sourceWeb.ServerRelativeUrl + sourceList);
                        Console.WriteLine("[{0}] Source set to: {1}", DateTime.Now.ToShortTimeString(), source);

                        // Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset
                        SPListItemCollection items = source.Items;

                        var fileCount = 0;

                        Console.WriteLine("[{0}] Opening Destination site: {1}", DateTime.Now.ToShortTimeString(), destinationSiteURL);

                        using (var destSite = new SPSite(destinationSiteURL))
                        {
                            Console.WriteLine("[{0}] Opened Destination site: {1}", DateTime.Now.ToShortTimeString(), destSite);

                            using (var destinationWeb = destSite.OpenWeb())
                            {

                                Console.WriteLine("[{0}] Destination Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(),
                                                  destinationWeb.ServerRelativeUrl);

                                // get destination library
                                var destination = destinationWeb.GetList(destinationWeb.ServerRelativeUrl + destinationList);
                                Console.WriteLine("[{0}] Destination set to: {1}", DateTime.Now.ToShortTimeString(), destination);

                                // Get the root folder of the destination we'll use this to add the files
                                SPFolder destinationFolder = destinationWeb.GetFolder(destination.RootFolder.Url);


                                Console.WriteLine("[{0}] Moving {1} files from {2} to {3} - please wait...", DateTime.Now.ToShortTimeString(),
                                                  items.Count, source, destination);


                                // Now to move the files and the metadata
                                foreach (SPListItem item in items)
                                {
                                    //Get the file associated with the item
                                    SPFile file = item.File;

                                    // Create a new file in the destination library with the same properties
                                    SPFile newFile = destinationFolder.Files.Add(destinationFolder.Url + "/" + file.Name, file.OpenBinary(),
                                                                                 file.Properties, true);

                                    // Optionally copy across the created/modified metadata                        
                                    if (retainMeta)
                                    {
                                        SPListItem newItem = newFile.Item;
                                        WriteFileMetaData(item, newItem);
                                    }

                                    // Delete the original version of the file
                                    // todo: make local backup before deleting?
                                    file.Delete();

                                    fileCount++;
                                }

                                Console.WriteLine("[{0}] Completed moving {1} files to {2}", DateTime.Now.ToShortTimeString(), fileCount,
                                                  destination);
                            }

                        }


                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        Console.WriteLine(
                            "[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.",
                            DateTime.Now.ToShortTimeString());

                        throw;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("[{0}] Exception: {1}", DateTime.Now.ToShortTimeString(), ex);

                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// Overwrite existing meta data for a file with meta data from another file
        /// </summary>
        /// <param name="sourceItem">Source file to take meta data from</param>
        /// <param name="destinationItem">Destination file to write meta data to</param>
        public static void WriteFileMetaData(SPListItem sourceItem, SPListItem destinationItem)
            // overwrites a list items meta data with meta data from another file
        {
            //todo: change to write individual items instead of using source item

            destinationItem["Editor"] = sourceItem["Editor"];
            destinationItem["Modified"] = sourceItem["Modified"];
            destinationItem["Modified By"] = sourceItem["Modified By"];
            destinationItem["Author"] = sourceItem["Author"];
            destinationItem["Created"] = sourceItem["Created"];
            destinationItem["Created By"] = sourceItem["Created By"];

            // UpdateOverwriteVersion() will preserve the metadata added above. 
            destinationItem.UpdateOverwriteVersion();
        }
    }

The method above MoveListItems works perfectly fine. Items move, meta data is retained and people are partying in the streets. Unfortunately the same cannot be said of MoveListItemsSiteToSite. With this method no error is thrown but no items are copied also. I can't figure out why and the output I'm being given shows that I'm feeding the right data in.

If you'd prefer another example the below is a program you can copy into any solution. I'm basically trying to change this to allow items to be copied from one site to another but I'm having no success... help?

public class Program
    {
        private static void Main(string[] args)
        {
            const string connectionString = @"http://Mdev/re/ad/wf";

            Console.WriteLine("## M Archiver started at: {0} ##", DateTime.Now);

            var fileCount=0;

            // Declare and initialize the new site
            Console.WriteLine("[{0}] Opening site: {1}", DateTime.Now.ToShortTimeString(), connectionString);
            using (var site = new SPSite(connectionString))
            {
                // open the site
                using (SPWeb web = site.OpenWeb())
                {


                    Console.WriteLine("[{0}] Opened site: {1}", DateTime.Now.ToShortTimeString(), web);
                    Console.WriteLine("[{0}] Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(), web.ServerRelativeUrl);

                    try
                    {
                        // Get your source and destination libraries
                        var source = web.GetList(web.ServerRelativeUrl + @"/Approval%20History%20%20Sales1");
                        var destination = web.GetList(web.ServerRelativeUrl + @"/Approval%20History%20%20Sales");

                        Console.WriteLine("[{0}] Source set to: {1}", DateTime.Now.ToShortTimeString(), source);
                        Console.WriteLine("[{0}] Destination set to: {1}", DateTime.Now.ToShortTimeString(), destination);

                        // Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset
                        SPListItemCollection items = source.Items;

                        // Get the root folder of the destination we'll use this to add the files
                        SPFolder folder = web.GetFolder(destination.RootFolder.Url);

                        Console.WriteLine("[{0}] Moving {1} files from {2} to {3} - please wait...", DateTime.Now.ToShortTimeString(),
                                          items.Count, source, destination);

                        // Now to move the files and the metadata
                        foreach (SPListItem item in items)
                        {
                            //Get the file associated with the item
                            SPFile file = item.File;

                            // Create a new file in the destination library with the same properties
                            SPFile newFile = folder.Files.Add(folder.Url + "/" + file.Name, file.OpenBinary(), file.Properties, true);

                            // Optionally copy across the created/modified metadata                        
                            SPListItem newItem = newFile.Item;
                            newItem["Editor"] = item["Editor"];
                            newItem["Modified"] = item["Modified"];
                            newItem["Modified By"] = item["Modified By"];
                            newItem["Author"] = item["Author"];
                            newItem["Created"] = item["Created"];
                            newItem["Created By"] = item["Created By"];

                            // UpdateOverwriteVersion() will preserve the metadata added above. 
                            newItem.UpdateOverwriteVersion();

                            // Delete the original version of the file
                            // todo: make local backup before deleting?
                            file.Delete();
                            fileCount++;
                        }

                        Console.WriteLine("[{0}] Completed moving {1} files to {2}", DateTime.Now.ToShortTimeString(), fileCount,
                                          destination);
                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        Console.WriteLine(
                            "[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.",
                            DateTime.Now.ToShortTimeString());
                    }
                    finally
                    {
                        web.Dispose();
                        site.Dispose();
                    }
                }
                Console.WriteLine("[{0}] All operations complete, exiting...", DateTime.Now.ToShortTimeString());
            }
        }
    }
share|improve this question
    
When you mean "site" you actually mean SPSite (site collection) or SPWeb (sub-site)? Tried this sharepointfieldnotes.blogspot.ch/2009/11/… –  C. Marius - MVP Aug 27 '12 at 7:51
    
The intent is to copy from a library contained in one site collection to one in another site collection –  ElvisLikeBear Aug 27 '12 at 8:01
    
then go ahead with the example, and let us know if it helped! –  C. Marius - MVP Aug 27 '12 at 8:13
    
@C.Marius Now resolved - thank-you for your help. Feel free to post as an answer if you'd like some karma for it :) –  ElvisLikeBear Aug 27 '12 at 23:18
    
Link has been posted as an answer. Thank you! –  C. Marius - MVP Aug 28 '12 at 9:45

1 Answer 1

up vote 1 down vote accepted

To copy files from one site collection to another a very good example is explained in this article http://sharepointfieldnotes.blogspot.ch/2009/11/how-to-copy-files-across-site.html

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.