How to OpenWebConfiguration with physical path?

aron picture aron · Mar 3, 2010 · Viewed 23.9k times · Source

I have a win form that creates a site in IIS7. One function needs to open the web.config file and make a few updates. (connection string, smtp, impersonation)

However I do not have the virtual path, just the physical path.

Is there any way I can still use WebConfigurationManager?

I need to use it's ability to find section and read/write.

System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration

Answer

Vadim Rybak picture Vadim Rybak · Mar 18, 2010

You will have to map the physicalPath to a virtualPath. Here is how you would do that.

using System.Web.Configuration;  //Reference the System.Web DLL (project needs to be using .Net 4.0 full, not client framework)

public static Configuration OpenConfigFile(string configPath)
{
    var configFile = new FileInfo(configPath);
    var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
    var wcfm = new WebConfigurationFileMap();
    wcfm.VirtualDirectories.Add("/", vdm);
    return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
}