从Windows服务读取web.config中定义的连接字符串

问题描述 投票:0回答:1

我正在尝试从Windows服务读取web.config中定义的连接字符串。站点名称为MySite,位于IIS的http://localhost:31000上,物理路径为C:\inetpub\wwwroot\MySite

问题是以下代码始终从系统级别的machine.config而非此站点的web.config读取连接字符串。我尝试了不同的设置和代码,但结果相同。我在做什么错?

var configFile = new FileInfo(@"C:\inetpub\wwwroot\MySite\web.config");
var vdm = new System.Web.Configuration.VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var wcfm = new System.Web.Configuration.WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
ConnectionStringsSection csSection = config.ConnectionStrings;
for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
{
  ConnectionStringSettings cs = csSection.ConnectionStrings[i];

  if (cs.Name == 'SQLServerConnectionString')
    return cs.ConnectionString;
}
c# iis web-config windows-services connection-string
1个回答
0
投票

应该简单得多。这就是从web.config文件读取连接字符串所需的全部。

<ConnectionStrings>
 <add name="SQLServerConnectionString" connectionString="" />
</ConnectionStrings> 

var connectionString = ConfigurationManager.ConnectionStrings["SQLServerConnectionString"].ConnectionString;