예제 #1
0
        public static SPList CopyList(SPList source, SPWeb webDestination, string destinationTitle, bool deleteIfExist)
        {
            SPList destinationList = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(webDestination.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb(webDestination.ID))
                    {
                        web.AllowUnsafeUpdates = true;
                        destinationList        = web.Lists.Cast <SPList>().Where(p => string.Compare(p.Title, destinationTitle) == 0).FirstOrDefault();

                        if (destinationList != null)
                        {
                            if (deleteIfExist)
                            {
                                destinationList.Delete();
                            }
                            else
                            {
                                return;
                            }
                            //throw new Exception("Destination list already exist");
                        }

                        try
                        {
                            Guid newListID  = web.Lists.Add(destinationTitle, string.Empty, SPListTemplateType.GenericList);
                            destinationList = web.Lists[newListID];

                            destinationList.ContentTypesEnabled = true;
                            destinationList.Update();

                            if (destinationList.ContentTypes.Cast <SPContentType>().FirstOrDefault(ct => ct.Name == "Item") != null &&
                                source.ContentTypes.Count > 1)
                            {
                                destinationList.ContentTypes["Item"].Delete();
                                destinationList.Update();
                            }

                            source.CopyAllFieldsToList(destinationList);

                            source.CopyAllContentTypesToList(destinationList);

                            source.CopyAllViewsToList(destinationList);
                        }
                        catch (Exception ex)
                        {
                        }
                        web.AllowUnsafeUpdates = false;
                    }
                }
            }
                                                 );

            return(destinationList);
        }