从Web.Config读取variables

我怎样才能添加和读取web.config文件的值?

我build议你不要从你的web.config中修改,因为每次更改时,都会重新启动你的应用程序。

但是,您可以使用System.Configuration.ConfigurationManager.AppSettings来读取web.config

鉴于以下web.config:

 <appSettings> <add key="ClientId" value="127605460617602"/> <add key="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/> </appSettings> 

用法示例:

 using System.Configuration; string clientId = ConfigurationManager.AppSettings["ClientId"]; string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"]; 

如果您需要基础知识,您可以通过以下方式访问密钥:

 string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString(); string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString(); 

要访问我的networkingconfiguration密钥,我总是在我的应用程序中创build一个静态类。 这意味着我可以在任何需要的地方访问它们,而且我不会在整个应用程序中使用string(如果它在Webconfiguration中发生更改,我将不得不通过所有更改它们的事件)。 这是一个示例:

 using System.Configuration; public static class AppSettingsGet { public static string myKey { get { return ConfigurationManager.AppSettings["myKey"].ToString(); } } public static string imageFolder { get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); } } // I also get my connection string from here public static string ConnectionString { get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; } } } 

假设该键包含在<appSettings>节点中:

 ConfigurationSettings.AppSettings["theKey"]; 

至于“写作” – 简单地说, 不要。

web.config不是为此devise的,如果你要不断地改变一个值,把它放在一个静态的帮助类中。

Ryan Farley在他的博客中有一篇很棒的文章,包括为什么不写回web.config文件的所有原因: 写入.NET应用程序的configuration文件

我是siteConfiguration类调用所有我的appSetting就像这样。 我分享它,如果它会帮助任何人。

在“web.config”中添加以下代码

 <configuration> <configSections> <!-- some stuff omitted here --> </configSections> <appSettings> <add key="appKeyString" value="abc" /> <add key="appKeyInt" value="123" /> </appSettings> </configuration> 

现在你可以定义一个类来获得你所有的appSetting值。 喜欢这个

 using System; using System.Configuration; namespace Configuration { public static class SiteConfigurationReader { public static String appKeyString //for string type value { get { return ConfigurationManager.AppSettings.Get("appKeyString"); } } public static Int32 appKeyInt //to get integer value { get { return ConfigurationManager.AppSettings.Get("appKeyInt").ToInteger(true); } } // you can also get the app setting by passing the key public static Int32 GetAppSettingsInteger(string keyName) { try { return Convert.ToInt32(ConfigurationManager.AppSettings.Get(keyName)); } catch { return 0; } } } } 

现在添加前一个类的引用,并访问像bellow一样的密钥调用

 string appKeyStringVal= SiteConfigurationReader.appKeyString; int appKeyIntVal= SiteConfigurationReader.appKeyInt; int appKeyStringByPassingKey = SiteConfigurationReader.GetAppSettingsInteger("appKeyInt");