mardi 3 avril 2012

Add attachements on SharePoint Item

Hi, developpers today i'm writing this duing to lack of information in the internet about adding attachements on sharepoint Item client side. So first of all if you are using "Client context" it's hight time to know that it cant do every thing for you.
This tutorial is about adding attachement using Sharepoint web services.
So if you are trying to do the same I think you are enought able to consume a web service. so try to connect on your sharepoint Web service (the one that ends with "http://your_domain/_vti_bin/lists.asmx")  and name it "ListsService 

ListsWebService.Lists ListsService = new ListsWebService.Lists();

Here you are with full controle on your sharepoint. So now you can start reading your file to attach.


 

 FileStream fStream = System.IO.File.OpenRead(filePath);
 byte[] contents = new byte[fStream.Length];
 fStream.Read(contents, 0, (int)fStream.Length);
 fStream.Close();

gooood nice #MOMTAZ you are ready to attach it to your Item, ToDo you have to know the ID of your Item on the sharepoint, Go Get it I'm weating for you, the ListName or GUID (I'm using the ID of the List) and the fileName. and just call the methode AddAttachement of the web service.

ListsService.AddAttachment(GUID, ItemId, fileName, contents);

I'm using thoes params as exemple: 
  • GUID:c3a01ef7-95ba-4230-8754-ea288f93fd31
  • ItemId: 250
  • fileName: doc1\folder2\XXXXX.docx (this is not an xxx content)
  • contents: {bytes[12]}

So this is what we got (just copy and have fun):

ListsWebService.Lists ListsService = new ListsWebService.Lists();
FileStream fStream = System.IO.File.OpenRead(filePath);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
ListsService.AddAttachment(GUID, ItemId, fileName, contents);