How To Iterate SharePoint Attachments Using The API

Looking for a way to iterate a SharePoint list item (SPListItem) for all attachments and render them on your page?  Here is a nice example....

private String x_renderAttachmentData(SPListItem listItem)
{
    String strAttachmentData = String.Empty;

    try
    {

        if (listItem.Attachments.Count > 0)
        {

            foreach (string fileName in listItem.Attachments)
            {
                SPFile spFile = listItem.ParentList.ParentWeb.GetFile(listItem.Attachments.UrlPrefix + fileName);
                int fileSize = (int)spFile.Length / 1000;
                strAttachmentData += "<div class='attachment'>"
                                   + "<img src='_layouts/images/" + spFile.IconUrl + "'> "
                                   + "<a target='_blank' href='" + URL_ROOT + "/" + spFile.Url + "'>"
                                   + spFile.Name + "</a> &nbsp; (" + fileSize + " KB)"
                                   + "<div class='hr'></div>Attachment version: " + spFile.UIVersionLabel
                                   + "<br/>Created at " + spFile.TimeCreated.ToString() + " by "
                                   + spFile.Author.ToString().Substring(spFile.Author.ToString().IndexOf('//') + 1)
                                   + "<br/>Last modified at " + spFile.TimeLastModified.ToString() + " by "
                                   + spFile.ModifiedBy.ToString().Substring(spFile.ModifiedBy.ToString().IndexOf('//') + 1)
                                   + "</div><div style='clear:left;'></div>";  // just call me a css genius.
               
            }
        }
        return strAttachmentData;

    }
    catch (Exception exp)
    {
        // handle exp.
    }
}

Output for this function looks like this... 

Here is the css if you are interested....

.attachment
{
 color:#999999;
 font-size:9px;
 margin-bottom:0px;
 float:left;
}
.attachment img{margin-bottom:-2px;}
.attachment .hr
{
 border-top:1px solid #bbbbbb;
 margin-top:2px;
}
.attachment a:link,
.attachment a:visited,
.attachment a:hover
{
 font-size:14px;
 line-height:18px;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值