Here is steps to get sharepoint list item attachment programmatically.
- Follow the steps to insert new item into your sharepoint list.
- Create new instance of site with your current application
using
(SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{
-
Create new web instance and open web for current application
using (SPWeb
web = site.OpenWeb())
{
- Create new list object and get your list
SPList SPLData = web.Lists["Your List Name"];
- Create new query object
to hold query which fetches list item of the list
SPQuery SPMyQuery = new
SPQuery();
- Assign query with value to it in ID field of the list item
SPMyQuery.Query = string.Format(“<Where
> < Eq
> < FieldRef Name='ID' /
> < Value
Type='Counter'
> {0}
< /Value
> < /Eq
> < /Where
>”,1);
- Assign
query to list and get item on the basis of the query build above
SPListItemCollection common = SPLData.GetItems(SPMyQuery);
- Check
whether list collection contains result of the query, if contains item the
proceed to update value of the list item
if (common.Count > 0)
{
SPListItem mylistItem = common[0];
string[] _Str_Attachments =
GetAttachmentCollection(mylistItem);
- You can assign attachment collection
with grid and if you want to give link to the attachment filename, on each file
name with anchor link put following code for href of
anchor.
string.Format("/Lists/{0}/Attachments/{1}/{2}", "Your List
Name”,1,”FileName”);
}
}
}
- Get sharepoint list item
attachment collection
public string[] GetAttachmentCollection(SPListItem
item)
{
string FileNames =
String.Empty;
if (item.Attachments.Count > 0)
{
string[] _Str_File_Name = new
string[item.Attachments.Count];
for (int i = 0; i <
item.Attachments.Count; i++)
{
SPFile
file = item.ParentList.ParentWeb.GetFile(item.Attachments.UrlPrefix +
item.Attachments[i].ToString());
_Str_File_Name[i]=
file.Name;
}
return
_Str_File_Name;
}
return null;
}
-That’s it for fetching attachments for existing item of sharepoint
list.