Get SharePoints Database names and connection strings.

C Sharp source code for grabbing database details in sharepoint

Using Sharepoint’s internal mechanisms, it is possible to retrieve the database name and connection string for the content databases that power a site. The code in the attached file uses the following methodology.

1) create a new topology object.
2) loop through objTopology.Databases
3) test whether the returned DB is a profile, Site or Server database
4) allow access to string[] objects that contain the database name and connection string for each type of database.

Simple*.

* It is a little bit hacky, though. I can’t find any methods that tell me database-X functions as the profiles database, or that database-Y is the Sites database. To do this, I have had to resort to running queries against the database in question to determine whether a distinctive table exists. Not ideal, but until I find a better way, it will have to do.

**UPDATE**

The original version will fail if you try to get database details on a host with multiple portals. To get around this, you need to instantiate the object by passing in the site id.

for example:

// find the base url for this portal site.
string PortalUrl = Page.Request.Url.ToString().Replace(Page.Request.RawUrl.ToString(),”/”);
// Create a SPSite object
SPSite mySite = new SPSite(PortalUrl);
// Create a sharepointInfo object to get the databases back from
InTechnology.InTranet.SharepointInfo.Information myInfo = new InTechnology.InTranet.SharepointInfo.Information(mySite.ID.ToString());
profileConnectionString = myInfo.profilesDatabase()[1];

Again, I’m sure there is an easier way to get the site ID, but I don’t know it.