Finding an SPWebApplication by ID

Not sure if it was me that prompted Neil’s post, but a question that came up earlier today was how to retrieve an SPWebApplication from its ID. Neil suggested trying to retrieve the generic SPPersistedObject by that ID, which eventually led me to SPFarm.GetObject(Guid).

SPFarm farm = SPFarm.Local;
Guid webAppId = new Guid("e81de291-7205-42fe-8228-422c6bbed277");
SPWebApplication webApp = farm.GetObject(webAppId) as SPWebApplication;
Debug.WriteLine(webApp);

Have I overlooked another method, or is this really the only way?

Bonus tip: Use SPAdministrationWebApplication.Local to get the web app for Central Admin.

Advertisement

One Response to “Finding an SPWebApplication by ID”

  1. Neil Says:

    Keith,

    In my opinion, thats the best way if you only know the SPWebApplication guid. Otherwise you have to go through SPFarm and then to SPServer (or you could go straight to SPServer.Local if you were looking for a WebApp on the local machine). After that you look at the ServiceInstances, which is an SPServiceInstanceCollection. I think all the web apps are SPWebService, and then finally in there you can see the SPWebApplications that it corresponds with.

    And thats quite a bit of work! I think the SPPersistedObject approach, while not exactly intuitive, is easier to use than navigating the tree…especially if all you have is the guid!

    Neil


Comments are closed.

%d bloggers like this: