无法从web.config文件中读取邮件设置。[英] Cannot read mail settings form web.config file

问题描述


我使用以下代码读取配置文件,我只得到默认端口号,没有别的

请检查代码并告诉我应该做什么

Web.config 文件:

<system.net><邮件设置><smtp 来自="abinav@ymail.com"><网络主机="smtp.bizmail.yahoo.com" port="25" userName="abinav@ymail.com" 密码="Mypassword" defaultCredentials="true"/></smtp></mailSettings></system.net>

使用以下代码将物理路径转换为虚拟路径
public static 配置 OpenConfigFile(字符串配置路径){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, "/");}

使用上述方法读取配置文件
string strConfigPath = Server.MapPath("~/LeaveManagementSystem_30_01_2012/web.config");//strConfigPath = @"~/web.config";//HttpContext.Current.Request.ApplicationPath + "/"+ "web.config";配置 config = OpenConfigFile(strConfigPath) as 配置;MailSettingsSectionGroup mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;if (mailSettings != null){int port = mailSettings.Smtp.Network.Port;string host = mailSettings.Smtp.Network.Host;string 密码 = mailSettings.Smtp.Network.Password;string 用户名 = mailSettings.Smtp.Network.UserName;}


但是我只能读取默认端口设置,而不是 web.config 文件中提到的设置

推荐答案

仅使用以下代码....

System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);System.Net.Configuration.MailSettingsSectionGroup mailSettings = (System.Net.Configuration.MailSettingsSectionGroup) config.GetSectionGroup("system.net/mailSettings");if (mailSettings != null){int port = mailSettings.Smtp.Network.Port;string host = mailSettings.Smtp.Network.Host;string 密码 = mailSettings.Smtp.Network.Password;string 用户名 = mailSettings.Smtp.Network.UserName;}


你一定会得到你需要的一切......

本文地址:https://www.itbaoku.cn/post/1395186.html