Add Item to SharePoint List with attachment using client object model
Add Item to SharePoint List with attachment using client
object model
If your requirement is to add the item to a SharePoint list
with attachment using the client object model, this post will help you in this.
You can achieve this by following the below steps.
Step 1 – Define some constant variables those will hold the
values of SharePoint web service, List Id, etc.
private const string siteUrl = "http://appsuat.portal.intranet.aegonuk.com/sites/genapps/CashFlowsCashPositions";
private const string spWebServiceUrl = "http://appsuat.portal.intranet.aegonuk.com/sites/genapps/CashFlowsCashPositions/_vti_bin/Lists.asmx";
private const string updateSOAPAction = "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems";
private const string
addAttachSOAPAction = "http://schemas.microsoft.com/sharepoint/soap/AddAttachment";
private const string lstId
= “{BC50D967-CDB9-41B5-88BE-4F19A8626847}”
Step 2 – Build the xml string and add all the required
filed in below format. If there is space between the field names then fill that
space with “_x0020_” value.
strBatchXml = "" + strBatchXml + "
";
Step 3 – Make a POST call
using the WebRequest class.
WebRequest req = WebRequest.Create(spWebServiceUrl);
req.Method = "POST";
req.ContentType = "text/xml;
charset='UTF-8'";
req.Headers.Add("SOAPAction", updateSOAPAction);
req.Credentials = System.Net.CredentialCache.DefaultCredentials;
string strSoapBody = "" + lstId + "
byte[] byteArray = Encoding.UTF8.GetBytes(strSoapBody);
req.ContentLength =
byteArray.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Step 4 – Parse the response
to get the item id. You can use the below xPath to get the item id
//UpdateListItemsResult//Results//Result//z:row
Step 5 – Attach file to the
list item.
FileStream sr = new FileStream(@"c:\Test\Test.txt", FileMode.Open);
byte[] contents = new byte[sr.Length];
WebRequest reqAtt = WebRequest.Create("http://appsuat.portal.intranet.aegonuk.com/sites/genapps/CashFlowsCashPositions/_vti_bin/Lists.asmx");
reqAtt.Method = "POST";
reqAtt.ContentType = "text/xml; charset='UTF-8'";
reqAtt.Credentials = System.Net.CredentialCache.DefaultCredentials;
strSoapBody = " +
"xmlns:xsd='http://www.w3.org/2001/XMLSchema' " +
"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> " +
"" + lstId + "
" +
"" + itemId.ToString() +
"
" +
"" + "Test.txt" + "
" +
"" + System.Convert.ToBase64String(contents)
+ "
" +
"
";
byte[] byteArray12 = Encoding.UTF8.GetBytes(strSoapBody);
reqAtt.ContentLength = byteArray12.Length;
Stream dataStream1 = reqAtt.GetRequestStream();
dataStream1.Write(byteArray12, 0, byteArray12.Length);
// Close the Stream object.
dataStream1.Close();
WebResponse response1 = reqAtt.GetResponse()
Comments