WCF hosted in IIS reading configuration section in *.config other than web.config

Sample: we have Test folder under the application root, we want to read the connection string in test.config in the Test folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Configuration;
using System.ServiceModel.Activation;

namespace WebApplication1
{
    public interface IService1
    {
        [OperationContract]
        string DoWork();
    }
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class Service1 : IService1
    {
        public void DoWork()
        {
            String physDir = HttpContext.Current.Request.PhysicalApplicationPath;
            WebConfigurationFileMap fileMap = new WebConfigurationFileMap();                    
            
            VirtualDirectoryMapping vDirMap =new VirtualDirectoryMapping(physDir + "Test", true);
            
            fileMap.VirtualDirectories.Add("/Test", vDirMap);
            VirtualDirectoryMapping vDirMapBase = new VirtualDirectoryMapping(physDir, true, "test.config");            
            fileMap.VirtualDirectories.Add("/", vDirMapBase);

            System.Configuration.Configuration config = WebConfigurationManager.OpenMappedWebConfiguration(fileMap,"/Test");

            ConnectionStringsSection connectionStringsSection =
                 config.GetSection("connectionStrings")
                 as ConnectionStringsSection;        
        }
    }
}
原文地址:https://www.cnblogs.com/LeoTang/p/2799272.html