0

I have a list of elements in Sharepoint, they have title, description and the option to have an attachment. It's the classic list.

I need to make a list of all these items, showing the kilobytes of the attachment.

The problem is that I cannot do a FileInfo, because the only path I know is the URI path: http://example.com/../attachments/delete.txt

How can i know the kbs without doing a webrequest that forces me to download the file to get this info.

SW4
  • 69,876
  • 20
  • 132
  • 137
netadictos
  • 7,602
  • 2
  • 42
  • 69

2 Answers2

3

Try this:

using (SPSite site = new SPSite("http://fsm/Lists/sample/AllItems.aspx"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["sample"];
        SPListItemCollection items = list.GetItems(new SPQuery());
        foreach (SPListItem item in items)
        {
            foreach (string attachment in item.Attachments)
            {
                // "http://fsm" + "Lists/sample/1_.000"
                Uri itemAddress = new Uri(new Uri(web.Url), item.Url);
                Uri attachmentAddress = new Uri(itemAddress, 
                    String.Format("Attachments/{0}/{1}", item.ID, attachment));
                SPFile file = web.GetFile(attachmentAddress.AbsoluteUri);
                Console.WriteLine("{0} have {1} bytes", file.Name, file.Length);
            }
        }
    }
}
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
  • Thanks for the info, but it is not a file in a SPDocumentLibrary, it is an attachment in a listitem that you can retrieve with: SPAttachmentCollection attachs= items[0].Attachments; Any idea? – netadictos Oct 08 '09 at 12:44
  • 2
    what about web.GetFile(item.Attachments[0]).Length ? – Rubens Farias Oct 08 '09 at 13:03
  • That gives you the length of characters of the name file – netadictos Oct 08 '09 at 15:16
  • @netadictos: isn't entirely correct; while code had a mistake building full url to address, pseudo-code gets file content length. could you please check this code again? – Rubens Farias Oct 08 '09 at 15:59
1

You can usually get the file size from a generic URI by making a HEAD request which fetches only the headers, and looking at the Content-Length header in the response.

System.Net.WebRequest req = System.Net.HttpWebRequest.Create("https://stackoverflow.com/robots.txt");
req.Method = "HEAD";
System.Net.WebResponse resp = req.GetResponse();
int ContentLength;
if(int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
{ 
    //Do something useful with ContentLength here 
}

(code from this stackoverflow question)

Community
  • 1
  • 1
Colin Pickard
  • 45,724
  • 13
  • 98
  • 148
  • This depends on how your target webserver is configured of course, you did not include any details on this. If you control the target webserver and the file system you are serving from, there are probably easier ways to do this – Colin Pickard Oct 08 '09 at 12:03