Forum Discussion
Programatically move documents to document library along with metadata columns and version history
Hi Team,
Need inputs in moving a copy of document along with its metadata columns and version history to a different document library using C# Console App (CSOM).
We are automating a scenario where we identify documents based on the document URL. Once identified , we need to move the document to a different document library along with the metadata columns and version history.
I was successful in reading the columns and associated data for the document using the below code.
private static Dictionary<string, Dictionary<string, object>> getListData(ClientContext ctxObject,string libraryName)
{
var list = ctxObject.Web.Lists.GetByTitle(libraryName);
FieldCollection fields = list.Fields;
ctxObject.Load(fields);
ctxObject.ExecuteQuery();
var columns = new List<string> { "ID" };
foreach(var f in fields)
{
if (f.InternalName.StartsWith("_") || f.InternalName.StartsWith("ows")) continue;
if((f.FieldTypeKind == FieldType.Text)|| (f.FieldTypeKind== FieldType.DateTime) || (f.FieldTypeKind==FieldType.User))
{
columns.Add(f.InternalName);
}
}
List<Expression<Func<ListItemCollection, object>>> allIncludes = new List<Expression<Func<ListItemCollection, object>>>();
foreach(var c in columns)
{
allIncludes.Add(items => items.Include(item => item[c]));
}
ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctxObject.Load(listItems, allIncludes.ToArray());
ctxObject.ExecuteQuery();
var sd = listItems.ToDictionary(k => k["Title"] as string, v => v.FieldValues);
foreach(var i in sd.Keys)
{
foreach(var c in columns)
{
Console.WriteLine("{0}:{1}", c, sd[i][c]);
}
}
return sd;
}
But not sure how to create the above fetched columns and associated data along with the document in the new document library . Please suggest possible design patterns and any code artifacts that support this kind of scenario.
Thanks and Regards,
Sivapratap
- Why not using the PnP to replicate your document library and the create the code required to move the documents from the source to the destination?
- Deleted
As Juan Carlos Mentioned PnP is your friend!
- sivapratap kurapatiCopper ContributorHi,
Sorry to ask. I am not exactly clear on what PnP does. To be frank, after seeing your comment i started browsing about what exactly PnP is. Can you share artifacts on how to use PnP to replicate document library ?
Many Thanks,
Sivapratap.- Deleted
You Could use Get template which is getting the whole site as xml.
then apply template to add everything to the site.
in the xml you can remove the items you do not want to copy to the other site. it is really easy Vesa Juvonen and his team putted out a lot of howto's about pnp provisioning.
- Brent EllisSilver ContributorIs the different library in the same site? Or a different site altogether?
- sivapratap kurapatiCopper Contributor
It is in the same site .