Code snippet: Copy list data between sites programmatically
private void button1_Click(object sender, EventArgs e)
{
MoveData();
}
private void MoveData()
{
string siteURL = "https://terminator:4400";
string fromList = "list1";
string toList = "list2";
string viewname = "{29F43EBD-2A32-443A-9419-D6C77585EAAA}"; // list2's allitems view GUID
string documentPath = @"C:\check.pdf";
string websrv = "https://terminator:4400/_vti_bin/Lists.asmx"; // list2's webservice
SPSite objSite = new SPSite(siteURL);
SPWeb objWeb = objSite.OpenWeb();
SPList objFromlist = objWeb.Lists[fromList];
SPList objTolist = objWeb.Lists[toList];
foreach(SPListItem listItem in objFromlist.Items)
{
AddItem(listItem.ID.ToString(), listItem[1].ToString(), toList, viewname, documentPath, websrv);
}
MessageBox.Show("Operation completed! Please check the data now.");
}
private void AddItem(string ID, string title, string toList, string viewname, string documentPath, string websrv)
{
string elements = @"<Method ID='" + ID + @"' Cmd='New'>
<Field Name='ID'>New</Field>
<Field Name='Title'>" + title + @"</Field>
</Method>";
string strRowID = "";
SendDocument(elements, documentPath, ref strRowID, toList, viewname, websrv);
}
public void SendDocument(string elements, string documentPath, ref string strRowID, string toList, string viewname, string websrv)
{
XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlElement updates = xmlDoc.CreateElement("Batch");
updates.SetAttribute("OnError", "Continue");
updates.SetAttribute("ListVersion", "1");
updates.SetAttribute("ViewName", viewname);
updates.InnerXml = elements;
XmlNode node = null;
MyLists.Lists listService = new MyLists.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = websrv;
string listName = toList;
string listServiceURL = websrv;
if (listServiceURL.Length > 0)
listService.Url = listServiceURL;
try
{
if (strRowID == "")
{
node = listService.UpdateListItems(
listName,
updates);
XmlDocument rtnListItems = new XmlDocument();
rtnListItems.LoadXml(node.OuterXml);
XmlNamespaceManager nsmListItems = new XmlNamespaceManager(rtnListItems.NameTable);
nsmListItems.AddNamespace("foo", "https://schemas.microsoft.com/sharepoint/soap/");
XmlNode ndTemp = rtnListItems.SelectSingleNode("//*/*/*/@ows_ID", nsmListItems);
if (ndTemp != null)
{
strRowID = ndTemp.InnerText;
}
else
throw new Exception("The row ID could not be determined after the update of the list!");
}
System.IO.FileStream fStream =
System.IO.File.OpenRead(documentPath);
string fileName = System.IO.Path.GetFileName(fStream.Name);//fStream.Name.Substring(42);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
try
{
string addAttach =
listService.AddAttachment(listName, strRowID, fileName, contents);
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message.ToString());
}
}