Find out the URL for the document library of a SharePoint document

sharepoint

If i know the URL for a document, can I find the URL for sharepoint document library in which the document is present. The following are two sample URLs for a SharePoint site. The first document is present under the root of a document library. The second document is present under a folder "folder1" within the document library. Appreciate if there is anyway to know the URL for a document library (http:///sites/site1/DocLib/Forms/AllItems.aspx).

http:///sites/site1/DocLib/a.doc
http:///sites/site1/DocLib/folder1/a.doc


Thanks for your replies. I am looking for a solution with MOSS OOTB web service or based on the URL pattern. Can we use any of these to acheive this please?

Thanks.

Best Answer

The SPWeb object has a GetFile method, which takes the full file url.

SPFile file = web.GetFile(yoururl);

Now it's easy to get to the SPList's url, by using the following:

string listUrl = file.Item.ParentList.DefaultViewUrl;

So, in a method together:

public string GetListUrlFromFileUrl(string fullFileUrl)
{
  using (SPSite site = new SPSite(fullFileUrl))
  {
    using(SPWeb myWeb = site.OpenWeb())
    {
      SPFile file = myWeb.GetFile(fullFileUrl);
      return file.Item.ParentList.DefaultViewUrl;
    }
  }
}

Make sure to reference Microsoft.Sharepoint.dll in your project as well.

Related Topic