To Access the attached File in Sharepoint List

I am in office, woking on data migration for one of my project module. I felt bored so came here to share some of my code and to write another blog.

Today I will show you how to Access the attached File in Sharepoint List, this is one of my intial stage code i wrote for one of the web part for Flash banner; this might helpfull for those who might looking for the same.

try
        {
            //Page.Request.Url.ToString()
            //”http://srv:17604

            Microsoft.SharePoint.SPSite _site = new SPSite(Page.Request.Url.ToString());
            Microsoft.SharePoint.SPWeb _web = null;
            Microsoft.SharePoint.SPList _newsList = null;
            //_web = _site.OpenWeb(“en”);

            if (_site.AllWebs.Count > 0)
            {
                //get the web in my case i was having the variations in my web collections so this is to choose the web

                if (Request.Url.AbsolutePath.ToLower().IndexOf(“/ar/”) >= 0)
                {
                    _web = _site.OpenWeb(“Ar”);
                }
                else
                {
                    _web = _site.OpenWeb(“En”);
                }
            }

            if (_web != null)
            {
                //get the Banner List  Put the nme list here
                _newsList = _web.Lists[strListName];

            }

           SPQuery query = new SPQuery();

           query.Query = “<OrderBy>” +
                                          “<FieldRef Name=’Title’ />” +
                                          “</OrderBy>” ;
           

            SPListItemCollection _myListItems = _newsList.GetItems(query);
           

             //string sFilePath = “”;
            bannerPath = _myListItems[0].Attachments.UrlPrefix;

            foreach (SPListItem currentItem in _myListItems)
            {
                SPAttachmentCollection currentAttachments = currentItem.Attachments;
                string urlString = “”;

                if (Convert.ToBoolean(currentItem[“Active”].ToString()))
                {
                    urlString = currentItem.Attachments.UrlPrefix;
                    int nofAttachments = currentAttachments.Count;
                    bannerPath = SPEncode.HtmlEncode(urlString); // the URL is also correctly dispayed
                   
                    string fileName;
                    string fileUrl;
                    for (int p = 0; p < 1; p++)
                    {
                        fileName = currentAttachments[p];
                        fileUrl = currentAttachments.UrlPrefix + fileName;
                        bannerPath = SPEncode.HtmlEncode(fileUrl);
                    }
                }
            }

        }

        catch (Exception ex)
        {

        }

Enjoy Coding. You cant learn until you code to solve prb.

Best Regards.