Monday, May 24, 2010

Attach file to list item programmatically using web service

Hi All,

In SharePoint if we want to attach a file to any existing list item and we are in any other asp.net or client / server application or just any other console application, then we can use SharePoint web services to attach a file to existing list item.

Here is a sample code to attach a file to existing list item.

Write down the below code and you are good to go. Just see the argument of addattachment method of lists.asmx web service. In my case, I am attaching my file to item which has ID 7.

See image before running this code.



private void button7_Click(object sender, EventArgs e)
{
string strFilePath= textBox1.Text;

if (!File.Exists(strFilePath))
{
throw new ArgumentException(String.Format("{0} does not exist",
strFilePath), "srcUrl");
}

FileStream Stream = File.OpenRead(strFilePath);
string fileName = Stream.Name.Substring(3);
byte[] contents = new byte[Stream.Length];
Stream.Read(contents, 0, (int)Stream.Length);
Stream.Close();


DownloadListItems.Lists objLists = new EncryptAndDecrypt.DownloadListItems.Lists();

objLists.Credentials = System.Net.CredentialCache.DefaultCredentials;

objLists.Url = "{site url}/_vti_bin/lists.asmx";

try
{
string addAttach = objLists.AddAttachment("DummyList", "7", fileName, contents);

}

catch (System.Web.Services.Protocols.SoapException ex)
{

}


}


See below image after running above code.



That is it. you have just attached your file to the existing list item.

1 comment:

Ayshine said...

Good Subject .But i didn't understand what do you enter at textBox1 .Could you please tell me is it an url or something else




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com