views:

213

answers:

2

Hi. 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://xxx.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.

+1  A: 

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("http://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)

Colin Pickard
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
+3  A: 

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
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
what about web.GetFile(item.Attachments[0]).Length ?
Rubens Farias
That gives you the length of characters of the name file
netadictos
@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