Wednesday, November 9, 2011

SPFile.Item => "The object specified does not belong to a list"

Today I had an SPException getting SPFile.Item with message "The object specified does not belong to a list". I used the code like this:
var web = site.RootWeb;
var file = web.GetFile("http://site.url/test/pages/page.aspx");
if (file.Exists){
   var item = file.Item;
}
And then the exception was thrown. The fix was very simple:
using (var web = site.OpenWeb("/test/pages/page.aspx", false))
var file = web.GetFile("/test/pages/page.aspx");
...
}
I'm thinking that the original exception appeared because we created SPFile object from the SPWeb which doesn't contain this file. So, seems that SPFile should be explicitly created from corresponding SPWeb.
And one more strange issue:
using (var web = site.OpenWeb("/test/pages/page.aspx", false))
opens web with server relative URL "/test" while
using (var web = site.OpenWeb("http://site.url/test/pages/page.aspx", false))
returns RootWeb :O

No comments:

Post a Comment