Pergunta

A seguir http://blogs.technet.com/b/stefan_gossner/archive/2007/08/30/deep-dive-into-the-sharepoint-content-deployment-and-migration-api-part-4.aspx fornece o código seguinte para importar e exportar um item usando a API Content Deployment and Migration.

using System;     
using System.Collections.Generic;     
using System.Text;     
using Microsoft.SharePoint;     
using Microsoft.SharePoint.Deployment;     
namespace WssOMtest     
{     
   class Program     
   {
       static void Main(string[] args)     
       {     
           // export     
           SPSite site = new SPSite("http://localhost:4000");     
           SPWeb web = site.OpenWeb("/");     
           SPList list = web.Lists["MyList"];     
           SPListItem listItem = list.Items[0];     
           SPExportObject exportObject = new SPExportObject();     
           exportObject.Id = listItem.UniqueId;

           exportObject.Type = SPDeploymentObjectType.ListItem;     
           SPExportSettings exportSettings = new SPExportSettings();     
           exportSettings.ExportObjects.Add(exportObject);     
           exportSettings.FileLocation = @"c:\export\CopyListItem";

           exportSettings.FileCompression = false;

           exportSettings.SiteUrl = "http://localhost:4000";

           SPExport export = new SPExport(exportSettings);

           export.Run();

           web.Dispose();

           // import

           SPImportSettings importSettings = new SPImportSettings();

           importSettings.SiteUrl = "http://localhost:4000";

           importSettings.FileLocation = @"c:\export\CopyListItem";

           importSettings.FileCompression = false;

           importSettings.RetainObjectIdentity = false;

           SPImport import = new SPImport(importSettings);

           EventHandler<SPDeploymentEventArgs> startedEventHandler = new EventHandler<SPDeploymentEventArgs>(OnStarted);

           import.Started += startedEventHandler;

           import.Run();

           // cleanup

           site.Dispose();

       }

       // event handler to assign a new parent to the orphaned image in the package

       static void OnStarted(object sender, SPDeploymentEventArgs args)

       {

           SPSite site = new SPSite("http://localhost:4000");

           SPWeb web = site.OpenWeb("/PressReleases");

           SPList list = web.Lists["TargetList"];

           SPImportObjectCollection rootObjects = args.RootObjects;

           foreach (SPImportObject io in rootObjects)

           {

               io.TargetParentUrl = list.RootFolder.ServerRelativeUrl;

           }

           web.Dispose();

           site.Dispose();

       }     
   }     
}

OK ótimo.Alterei as configurações para que ele use os nomes da minha lista e o URL do meu site.A exportação está funcionando muito bem.A importação não está funcionando.Estou executando o código em uma biblioteca de documentos.Nenhum erro é gerado, mas o item de conteúdo não está mudando a lista.

O que poderia dar errado?Mesmo se eu excluir o item original após a exportação, faça a importação sem alterar a lista pai, nada acontece.

Foi útil?

Solução

Testei seu código e descobri que o problema era que os arquivos criados durante a exportação não foram limpos corretamente no disco local.Implementei a lógica de exclusão de arquivos para garantir que Exportar e Importar funcionem bem.Observe, executei o Exportar e Importar com e sem FileCompression e ambos estão funcionando bem.Executei meu teste em duas bibliotecas de imagens.

Desculpe, não tive muito tempo para melhorar mais seu código, por exemplo.descartando corretamente os objetos SPWeb e SPSite.Espero que você faça isso sozinho.

O código atualizado está colado abaixo:

class Program
    {
        static void Main(string[] args)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // implementation details omitted
                SPSite site = new SPSite("http://mylocaldev/");
                SPWeb web = site.OpenWeb("/");
                SPList list = web.Lists["ParentPic"];
                SPListItem listItem = list.Items[0];

                try
                {
                    //delete the old files
                    DirectoryInfo dir = new DirectoryInfo(@"c:\export\CopyListItem");
                    foreach (System.IO.FileInfo file in dir.GetFiles()) file.Delete();                    

                    // export                        
                    SPExportObject exportObject = new SPExportObject();
                    exportObject.Id = listItem.UniqueId;

                    exportObject.Type = SPDeploymentObjectType.ListItem;
                    SPExportSettings exportSettings = new SPExportSettings();
                    exportSettings.ExportObjects.Add(exportObject);
                    exportSettings.FileLocation = @"c:\export\CopyListItem";

                    exportSettings.FileCompression = false;

                    //exportSettings.BaseFileName = "exportfile.cmp";

                    exportSettings.SiteUrl = "http://mylocaldev/";

                    SPExport export = new SPExport(exportSettings);

                    export.Run();

                }
                catch (Exception ex)
                {

                }
                finally { web.Dispose();}


                // import

                SPImportSettings importSettings = new SPImportSettings();

                importSettings.SiteUrl = "http://mylocaldev/";

                importSettings.FileLocation = @"c:\export\CopyListItem";

                importSettings.FileCompression = false;

                //importSettings.BaseFileName = "exportfile.cmp";

                importSettings.RetainObjectIdentity = false;

                SPImport import = new SPImport(importSettings);

                EventHandler<SPDeploymentEventArgs> startedEventHandler = new EventHandler<SPDeploymentEventArgs>(OnStarted);

                import.Started += startedEventHandler;

                import.Run();

                // cleanup

                site.Dispose();

            });

        }

        // event handler to assign a new parent to the orphaned image in the package

        static void OnStarted(object sender, SPDeploymentEventArgs args)
        {

            SPSite site = new SPSite("http://mylocaldev/");

            SPWeb web = site.OpenWeb("/");

            SPList list = web.Lists["ChildPic"];

            SPImportObjectCollection rootObjects = args.RootObjects;

            foreach (SPImportObject io in rootObjects)
            {

                io.TargetParentUrl = list.RootFolder.ServerRelativeUrl;

            }

            web.Dispose();

            site.Dispose();

        }
    }

Outras dicas

Felizmente, pouco antes de alguns dias eu estava trabalhando em tarefas semelhantes.

Eu tentei com o seu código fornecido.e quase está funcionando.

Mas concordo com @Falak que você deve escrever código com try/catch adequado e com padrão de codificação padrão do SharePoint.

Aqui, descobri que, uma vez que seu código deve funcionar perfeitamente, na segunda vez você deverá receber um erro, porque não está limpando seu Pasta de localização do arquivo qual é:"c:\exportar\CopyListItem".

Isso pode ser uma ajuda para você.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a sharepoint.stackexchange
scroll top