Get SharePoint list item attachments using lists.asmx

In this post we will learn how can we get attachments of a list item from SharePoint using OOB list.asmx service provided by SharePoint.

Assuming you have added service reference in you project, Below is the code:

Where ->

id: The item id whose attachments are to fetched.

Kz: The service object.

ListServiceUrl: Is the key forservice url for example http:///_vti_bin/Lists.asmx

sourcelist: Is the name of the list whose item’s attachments are to be fetched.

GetXElement definition is also given below:

The function would return Key value pairs with file name as key and it’s data as value.

public static List<KeyValuePair<string, byte[]>> GetAttachementsall(string id)
{
var attch = new List<KeyValuePair<string, byte[]>>();
try{
Kz.Lists listService1 = new Kz.Lists();
listService1.Url = ConfigurationManager.AppSettings["ListServiceUrl"];
listService1.UseDefaultCredentials = true;

XmlNode retNode1 = listService1.GetAttachmentCollection(ConfigurationManager.AppSettings["sourcelist"], id);

XElement xl = GetXElement(retNode1);
XNamespace s = "http://schemas.microsoft.com/sharepoint/soap/ ";

var items = from i in xl.Elements(s + "Attachment") select new { File = i.Value };

WebClient Client = new WebClient();
Client.UseDefaultCredentials = true;

foreach (var item in items){

byte[] data = Client.DownloadData(item.File);
string fileName = Path.GetFileName(item.File);
attch.Add(new KeyValuePair<string, byte[]>(fileName, data));

}

}
catch (Exception ex){
Log.WritetoLog("Exception in Getting Attachments " + ex);
}
return attch;

}

public static XElement GetXElement(XmlNode node){
XDocument xDoc = null;
try{
xDoc = new XDocument();
using (XmlWriter xmlWriter = xDoc.CreateWriter())
node.WriteTo(xmlWriter);
}
catch (Exception ex){
Log.WritetoLog("Exception in Converting to Xelement " + ex);
}
return xDoc.Root;
}

Let me know if their are any questions left.

Keep SharePointing..

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s