Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Situation: I only have the full URL of an image in our farm & no knowledge of where it comes from other than being in the web application so I need to locate the site/web/list/item segments.

Since I will already know the WebApplication this is my function

 public string GetSiteUrl(SPWebApplication webapp, string FullUrl){
      return result = webapp.Sites.Where( s=>FullUrl.Contains(s.Url)).Select(s => s.url).OrderByDescending( s => s.length).First())
 }

assuming it is the valid url for an image, 'results' will contain my URL, but does this cause a memory leak since webapp.Sites is enumerated but not disposed ?

I also then intend to use a similar Linq query to get the SPWeb Url from SPSite.AllWebs

share|improve this question
1  
I just wouldn't use Linq :) blog.furuknap.net/why-linq-to-sharepoint-is-a-bad-idea You can write the equivalent of that in like 10 lines and not have to worry about whether or not the objects are being disposed. –  RJ Cuthbertson Feb 25 at 17:34
1  
I felt this way for a long time but I did some comparisons for sorting time between Linq & custom sorts; Linq was such an improved speed I started to have more faith, a little to much as it would seem. Thanks for the article, great read. –  user13186 Feb 26 at 17:33

1 Answer 1

up vote 2 down vote accepted

Your code will instantiate every SPSite in the web application which will cause two problems:

  1. It'll be very slow if you have many Site collections in the Web Application

  2. It'll leak memory unless you dispose all of the SPSites.

This implementation will be a lot faster and won't leak:

public string GetSiteUrl(SPWebApplication webapp, string FullUrl) {
  using (var site = new SPSite(FullUrl))
  {
    return site.FullUrl;
  }
}

Just calling the SPSite constructor with a Url of something in SharePoint will give you back the best matching Site Collection, if you then use site.OpenWeb() you'll get the best matching Site.

share|improve this answer
    
Very glad to know it does leak. I had tested this approach in PowerShell, it did not work there I assumed it would fail in C# as well. I was wrong. Thanks! –  user13186 Feb 26 at 17:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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