Search code examples
c#-3.0web-configwebconfigurationmanagervirtual-path

How to OpenWebConfiguration with physical path?


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

Solution

  • 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, "/");
    }