0

I am currently trying to retrive a Sharepoint item given it's URL. The URL would be an absolute URL or a relative URL.

To achieve this, I am using the SPWeb.GetListItem(string url) method. I observed a strange behavior when I use this method on my Sharepoint server against a particular site collection.

Assume that I have Site Collection SC and sites S1 and S2 under SC. Each of S1 and S2 have some Announcement items under them. A sample URL for an announcement is shown below

for e.g. Announcement1 - http://myserver.com/sites/SC/S1/Lists/Announcements/1_.000 Announcement2 - http://myserver.com/sites/SC/S2/Lists/Announcements/1_.000

I then use the following code snippet to attempt fetching the Announcement item with it's URL.

using(SPSite spSite = new SPSite("http://myserver.com/sites/SC")
{
    foreach(SPWeb web in spSite.AllWebs)
    {
        SPListItem item = web.GetListItem("http://myserver.com/sites/SC/S1/Lists/Announcements/1_.000");
        if(item != null)
        {
            Console.WriteLine("Item web title : " + web.Title);
        }
        else
        {
            Console.WriteLine("Item not found in web : " + web.Title);
        }  
        web.Dispose();
    }
}

My expected output would be:

Item web title : S1
Item not found in web : S2

However, my actual output is:

Item web title : SC
Item web title : S1
Item web title : S2

This is strange since given a absolute URL, the item should have been found only within S1 and not within the SC and S2 sites.

Can someone help me understand what I am missing out here?

4
  • 2
    seems you are recurring through the various webs, but the link to the item is always the same, so you are not really looking in the current web Commented Oct 8, 2014 at 11:02
  • @TiagoDuarte Thanks for the note. Can you help me understand what you mean by current web? This is my first time with Sharepoint. I am under the impression that since I am calling the method on every instance of the SPWeb, that instance is indeed the current instance. Commented Oct 8, 2014 at 11:25
  • @TiagoDuarte Also, I checked that printing the SPListItem.Web.Title also generates the same output Commented Oct 8, 2014 at 11:32
  • 2
    you have 3 webs. the root web, s1 and s2. you are iterating through all of them. however, since you are using an absolute url, it doesnt really matter whether you are in the context of root, s1 or s2, because the item always exists. you should try a relative url Commented Oct 8, 2014 at 11:39

1 Answer 1

1

The line

SPListItem item = web.GetListItem("http://myserver.com/sites/SC/S1/Lists/Announcements/1_.000");

is always true. So the Output is always in the first section for all webs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.