WebConfigurationManager.OpenWebConfiguration() - Failed to resolve the site ID
I am writing a small administrative tool to read configuration settings from web.config files for various websites that are running on the same web server as the tool. Initially I thought the method WebConfigurationManager.OpenWebConfiguration(), and the various overloads, would have been able to help me out. The method signature is exactly what I am trying to do:
The WebConfigurationManager class (System.Web.Configuration.WebConfigurationManager) has a method named OpenWebConfiguration which can open a configuration file located at a specific virtual path and for a specified IIS site.
This sounded perfect and exactly what I was trying to do until I ran into this exception when I first tried it:
Failed to resolve the site ID for 'otherwebsite.local'.
After digging around a bunch and confirming I had the parameters spelled correctly I finally found this post: Thread: Unable to open web configuration on non default websites.
It turns out that because the adminwebsite.local is in an application pool named adminwebsite.local and otherwebsite.local is in a different application pool named otherwebsite.local, they can’t talk to each other. To prove this, I moved otherwebsite.local into the adminwebsite.local application pool and the OpenWebConfiguration method worked perfectly.
So if the two websites could live in the same application pool then the WebConfigurationManager.OpenWebConfiguration() method would have worked great for the tool I am writing.
But unfortunately this is not how the web server is setup and not the recommended best practice (to have all websites in the same application pool). So I switched to a more brute force method of reading and parsing the config file as an XML document (using a Dataset object to do the heavy lifting):
DataSet ds = new DataSet();
ds.ReadXml(path + \\web.config);
DataTable dt = ds.Tables["appSettings"];
DataRow[] appSettings= dt.Rows[0].GetChildRows("appSettings_add");
foreach (DataRow appSetting in appSettings)
{
String str = Convert.ToString(appSetting["key"]);
//Do other work here....
}
ds.Dispose();