Tuesday, September 17, 2013

Retrieving attachments in SharePoint list Item

Retrieving the SharePoint List Item through OM model requires little tweaked. So you will get the meta data of your attached files in the specific Item. Code goes here.I am trying to retrieve the attached files from the First Item in the List.
public List GetAttachments(int itemId)
        {
            List fNAme = new List();
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    string sp = string.Empty;
                    var list = web.Lists["Case List"];
                    SPListItem item = list.GetItemById(1);
                    SPAttachmentCollection cols = item.Attachments;
                    SPFolder folder = web.Folders["Lists"].SubFolders[list.Title].SubFolders["Attachments"].SubFolders[item.ID.ToString()];
                    FileDetails f = null;
                    foreach (SPFile file in folder.Files)
                    {
                        f = new FileDetails();
                        f.FileName = file.Name;
                        f.FUrl = web.Url + file.ServerRelativeUrl;
                        SPUser user = file.ModifiedBy;
                        f.ModifiedBy = user.Name;
                        f.FVersion = file.MajorVersion.ToString();
                        f.fIcon = file.IconUrl;
                        fNAme.Add(f);
                    }

                }

            }
            return fNAme;
        }
       
Get and Set class for the File Details
public class FileDetails
    {
       public string FileName { get; set; }
       public string ModifiedBy { get; set; }
       public string FUrl { get; set; }
       public string FVersion { get; set; }
       public string fIcon { get; set; }
    }