Is it possible to use some built in SharePoint API to open a file no matter which web and library it's in?


Given the file: /subsiteA/PublishingImages/myimage.jpg I want to open it and get the list item, but using this fails:

var url = "/subsiteA/PublishingImages/myimage.jpg";
var file = SPContext.Current.Site.RootWeb.GetFile(url);
SPListItem item = file.GetListItem(); //Fails here with item not in library error

Naturally it will not work as the file is not located in the root web, but is there a generic way to locate the file no matter which web and library it's in and retrieve the SPListItem object related to the file?


Very similar to above, the SPSite object does actually remember the URL it was opened with - so you don't have to give a Web name. You should be able to use something like:

string url= "Full URL to File";
using (SPSite site = new SPSite(url)){
  using (SPWeb web = site.OpenWeb()) 
    SPFile file = web.GetFile(url); 
    SPListItem item = file.ListItemAllFields; 
  • This worked perfectly! Though it seems like sort of a hack or maybe more like a "hidden feature". – Thomas Jul 30 '12 at 12:02
  • Yeah, it isn't obvious that that should work. It's definitely not a hack - it's how parts of SharePoint work internally - but it could be better documented. – Andy Burns Jul 30 '12 at 16:30
  • Just did a quick test and it works fine with "_layouts" urls too :) – Thomas Jul 31 '12 at 5:57

I don't think it is possible to get file in such a way. I also really wanted to know if possible.

Other way, you have to code like:

using (SPSite site = new SPSite("yoursiteurl")){

using (SPWeb web = site.OpenWeb("subsiteA"))
    SPFile file = web.GetFile("/subsiteA/PublishingImages/myimage.jpg");
    SPListItem item = file.ListItemAllFields;


  • This is close to the code I'm currently using, but my problem is that the image can come from any web. In my case I can split the string on "PublishingImages", but I was hoping to find some code that would allow me to make the code work for any library. Another alternative would be to split the string on "/" and attempt to open webs recursively down, but that is very expensive. – Thomas Jul 30 '12 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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