// </Snippet16> // <Snippet17> // Show how to use OpenWebConfiguration(string, string, // string, string). // It gets he appSettings section of a Web application // running on the specified server. // If the server is remote your application must have the // required access rights to the configuration file. static void OpenWebConfiguration4() { // Get the configuration object for a Web application // running on the specified server. // Null for the subPath signifies no subdir. System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration( "/configTest", "Default Web Site", null, "myServer") as System.Configuration.Configuration; // Get the appSettings. KeyValueConfigurationCollection appSettings = config.AppSettings.Settings; // Loop through the collection and // display the appSettings key, value pairs. Console.WriteLine("[appSettings for Web app on server: myServer]"); foreach (string key in appSettings.AllKeys) { Console.WriteLine("Name: {0} Value: {1}", key, appSettings[key].Value); } Console.WriteLine(); }
private void LoadGraphThrottlingSettings(KeyValueConfigurationCollection appSettings) { var defThreshold = 50; var defDelayPerNode = 5; var defMaxRenderDelay = 1000; var defMinRenderCountForLongDelay = 10; if (appSettings == null) { NodeThresholdCountForThrottling = defThreshold; MillisecondsToDelayPerNodeWhenThrottling = defDelayPerNode; MaximumRenderShortDelay = defMaxRenderDelay; MinimumRenderCountToTriggerLongDelay = defMinRenderCountForLongDelay; return; } // Fetch NodeThresholdCountForThrottling setting string result = appSettings["NodeThresholdCountForThrottling"]?.Value ?? string.Empty; NodeThresholdCountForThrottling = !int.TryParse(result, out var settingValue) ? defThreshold : settingValue; // Fetch MillisecondsToDelayPerNodeWhenThrottling setting result = appSettings["MillisecondsToDelayPerNodeWhenThrottling"]?.Value ?? string.Empty; MillisecondsToDelayPerNodeWhenThrottling = !int.TryParse(result, out settingValue) ? defDelayPerNode : settingValue; // Fetch MaximumRenderShortDelay setting result = appSettings["MaximumRenderShortDelay"]?.Value ?? string.Empty; MaximumRenderShortDelay = !int.TryParse(result, out settingValue) ? defMaxRenderDelay : settingValue; // Fetch MinimumRenderCountToTriggerLongDelay setting result = appSettings["MinimumRenderCountToTriggerLongDelay"]?.Value ?? string.Empty; MinimumRenderCountToTriggerLongDelay = !int.TryParse(result, out settingValue) ? defMinRenderCountForLongDelay : settingValue; }
public override object EvaluateExpression(string expression, object parseTimeData, Type propertyType, IServiceProvider serviceProvider) { KeyValueConfigurationCollection customSettings = null; if (serviceProvider != null) { IWebApplication webApp = (IWebApplication)serviceProvider.GetService(typeof(IWebApplication)); if (webApp != null) { Configuration config = webApp.OpenWebConfiguration(true); if (config != null) { AppSettingsSection settingsSection = config.AppSettings; if (settingsSection != null) { customSettings = settingsSection.Settings; } } } } if (customSettings != null) { return(customSettings[expression]); } return(expression); }
/// <summary> /// Source: https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings?view=netframework-4.8 /// </summary> /// <param name="config"></param> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> private static bool AddUpdateAppSettings(Configuration config, string key, string value) { try { AppSettingsSection section = config.GetSection("appSettings") as AppSettingsSection; if (section != null) { KeyValueConfigurationCollection settings = section.Settings; if (settings[key] == null) { settings.Add(key, value); } else { settings[key].Value = value; } config.Save(ConfigurationSaveMode.Modified); return(true); } } catch (Exception e) { HandleConfigError(e); } return(false); }
private void LoadParserMessageFontSettings(KeyValueConfigurationCollection appSettings) { var defFontFamily = FontFamily.GenericSerif; var defFontSize = 8.25f; if (appSettings == null) { ParserMessageFontFamily = FontFamily.GenericMonospace; ParserMessageFontSize = defFontSize; return; } // Fetch EditorFontFamily setting var result = appSettings["ParserMessageFontFamily"]?.Value ?? string.Empty; try { ParserMessageFontFamily = !string.IsNullOrEmpty(result) ? new FontFamily(result) : defFontFamily; } catch (ArgumentException) { ParserMessageFontFamily = defFontFamily; } // Fetch EditorFontSize setting result = appSettings["ParserMessageFontSize"]?.Value ?? string.Empty; ParserMessageFontSize = !float.TryParse(result, out var settingValueFloat) ? defFontSize : settingValueFloat; }
private void TestServicesPaths() { KeyValueConfigurationCollection appSettings = GetServicesAppSettings(); bool allPathOK = true; foreach (string key in appSettings.AllKeys) { string value = appSettings[key].Value; if (value.StartsWith("~/")) { string fullPath = Server.MapPath(value); if (!Directory.Exists(fullPath) && !File.Exists(fullPath)) { MarkAsFail(ServicesFilePathLabel, "Invalid path: " + key + "=" + fullPath, string.Empty); allPathOK = false; } } else if (Path.IsPathRooted(value) && !value.StartsWith(@"\") && !value.StartsWith(@"/")) { if (!Directory.Exists(value) && !File.Exists(value)) { MarkAsFail(ServicesFilePathLabel, "Invalid path: " + key + "=" + value, string.Empty); allPathOK = false; } } } if (allPathOK) { MarkAsPass(ServicesFilePathLabel); } }
private static string GetConfigurationValue(string key) { object settings = Configuration.Settings; if (settings != null) { KeyValueConfigurationCollection keyValueConfigurationCollection = settings as KeyValueConfigurationCollection; if (keyValueConfigurationCollection != null) { KeyValueConfigurationElement keyValueConfigurationElement = keyValueConfigurationCollection[key]; if (keyValueConfigurationElement == null) { return(null); } return(keyValueConfigurationElement.Value); } else { NameValueCollection nameValueCollection = settings as NameValueCollection; if (nameValueCollection != null) { return(nameValueCollection[key]); } } } return(null); }
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public static void Register(HttpConfiguration config) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member { // Web API configuration and services // Get Application settings from Web.Config KeyValueConfigurationCollection settings = WebConfigurationManager.OpenWebConfiguration("/").AppSettings.Settings; // Enable Cross Origin Resource Sharing (PM>Install-Package Microsoft.AspNet.WebApi.Cors) var corsSettings = new EnableCorsAttribute( origins: settings["AllowedOrigins"].Value, methods: settings["AllowedMethods"].Value, headers: settings["AllowedHeaders"].Value); corsSettings.SupportsCredentials = true; // Allow sending of credentials from the host. config.EnableCors(corsSettings); // Configure Web API to use only bearer token authentication. // config.SuppressDefaultHostAuthentication(); // config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "data/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
// ctor // Note: our errors will be in the inner exception. static AppConfig() { // Get the settings try { config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); settings = config.AppSettings.Settings; } catch (Exception ex) { string s = $"Couldn't open app configuration: {ex.Message}"; throw new Exception(s); } // Create config file if needed if (File.Exists(config.FilePath)) { return; } try { CreateConfigFile(config.FilePath); config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); settings = config.AppSettings.Settings; } catch (Exception ex) { string s = $"Couldn't create app config file: {ex.Message}"; throw new Exception(s); } }
public string this[string key] { get { try { return(ConfigurationManager.AppSettings[key] ?? null); } catch { return(null); } } set { try { Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection settings = appConfig.AppSettings.Settings; if (settings[key] == null) { settings.Add(key, value); } else { settings[key].Value = value; } appConfig.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(appConfig.AppSettings.SectionInformation.Name); } catch { } } }
/// <summary> /// Retrieves a value for a specified property from a configuration collection. /// </summary> /// /// <param name="SettingsCollection"> /// The configuration collection containing the settings values. /// </param> /// /// <param name="FullKeyName"> /// The key name in the collection. /// </param> /// /// <param name="KeyName"> /// The key name associated with a property in this class. /// </param> /// private void DetermineConfigFromSettings(KeyValueConfigurationCollection SettingsCollection, string FullKeyName, string KeyName) { string keyValue = SettingsCollection[FullKeyName].Value; switch (KeyName.ToUpper()) { case "DATASOURCE": this.DataSource = keyValue; break; case "USERID": this.UserID = keyValue; break; case "PASSWORD": this.Password = keyValue; break; case "INTEGRATEDSECURITY": this.IntegratedSecurity = Convert.ToBoolean(keyValue); break; case "INITIALCATALOG": this.InitialCatalog = keyValue; break; case "SERVICE": this.Service = keyValue; break; } }
public static bool AddUpdateSetting(string key, string value) { try { lock ( m_lock ) { Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (configFile == null) { return(false); } KeyValueConfigurationCollection settings = configFile.AppSettings.Settings; if (settings[key] == null) { settings.Add(key, value); } else { settings[key].Value = value; } configFile.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name); } }catch (ConfigurationErrorsException e) { System.Diagnostics.Debug.WriteLine("Error while writing app settings: {0}", e.Message); } return(true); }
public void LoadConfigure() { openFileDialog.Title = Resources.加载配置文件; openFileDialog.Filter = Resources.配置文件Filter; if (openFileDialog.ShowDialog(this) == DialogResult.OK) { try { ExeConfigurationFileMap filemap = new ExeConfigurationFileMap(); filemap.ExeConfigFilename = openFileDialog.FileName; Configuration con = ConfigurationManager.OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None); AppSettingsSection WordMakeSetings = con.Sections["WordMakeSetings"] as AppSettingsSection; if (WordMakeSetings == null) { MessageBox.Show(this, "选择的文件并不包含可以的配置信息!"); } KeyValueConfigurationCollection keyv = WordMakeSetings.Settings; Settings settings = Settings.Default; foreach (KeyValueConfigurationElement kValue in keyv) { object old = settings[kValue.Key]; settings[kValue.Key] = TypeDescriptor.GetConverter(old).ConvertFrom(kValue.Value); } } catch (Exception ee) { MessageBox.Show(this, ee.ToString()); } } }
// </Snippet18> // <Snippet19> // Show how to use OpenWebConfiguration(string, string, // string, string, IntPtr). // It gets he appSettings section of a Web application // running on a remote server. // If the serve is remote your application shall have the // requires access rights to the configuration file. static void OpenWebConfiguration6() { IntPtr userToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token; string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // Get the configuration object for a Web application // running on a remote server. System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration( "/configTest", "Default Web Site", null, "myServer", userToken) as System.Configuration.Configuration; // Get the appSettings. KeyValueConfigurationCollection appSettings = config.AppSettings.Settings; // Loop through the collection and // display the appSettings key, value pairs. Console.WriteLine( "[appSettings for Web app on server: myServer user: {0}]", user); foreach (string key in appSettings.AllKeys) { Console.WriteLine("Name: {0} Value: {1}", key, appSettings[key].Value); } Console.WriteLine(); }
/// <summary> /// Initializes and loads the default app configuration to use. /// </summary> public static void Init() { var currentAppLocation = System.Reflection.Assembly.GetExecutingAssembly().Location; appConfiguration = ConfigurationManager.OpenExeConfiguration(currentAppLocation); appSettings = appConfiguration.AppSettings.Settings; }
public void RefreshCache() { Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(_configFileMap, ConfigurationUserLevel.None); var section = (AppSettingsSection)configuration.GetSection(APP_SETTINGS); _settings = section.Settings; }
private DefaultEntries() { Configuration exeConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); this.loadedDefaultConfig = exeConfig.AppSettings.Settings; Logger.Debug(string.Format("Loading application settings from {0}", exeConfig.FilePath)); this.Url = "https://"; this.Name = Environment.UserName; this.Binding = null; this.CanModifyUrl = true; if (this.loadedDefaultConfig["Url"] != null) { this.Url = this.loadedDefaultConfig["Url"].Value ?? "https://"; } if (this.loadedDefaultConfig["Name"] != null) { this.Name = this.loadedDefaultConfig["Name"].Value ?? Environment.UserName; } if (this.loadedDefaultConfig["Binding"] != null) { this.Binding = this.loadedDefaultConfig["Binding"].Value; } if (this.loadedDefaultConfig["UrlModificationAllowed"] != null) { bool canModify; if (Boolean.TryParse(this.loadedDefaultConfig["UrlModificationAllowed"].Value, out canModify)) { this.CanModifyUrl = canModify; } } }
private static void AssertProviderReturnsAllProperties <T, TF>(TF factory, KeyValueConfigurationCollection settingsCollection) where T : class, IEnvironmentInfoProvider where TF : class, IEnvironmentInfoProviderFactory { var provider = factory == null?TypeFactory.Get <T>() : factory.Get <T>(); foreach (var propertyInfo in provider.GetType().GetProperties()) { if (propertyInfo.Name.Contains("Mock")) { continue; } if (propertyInfo.PropertyType.IsArray) { var expected = settingsCollection[propertyInfo.Name].Value.Split(';'); var actual = propertyInfo.GetValue(provider, null); //assert CollectionAssert.AreEqual(expected, (string[])actual); } else { var expected = settingsCollection[propertyInfo.Name].Value; var actual = propertyInfo.GetValue(provider, null); //assert Assert.AreEqual(expected, actual); } } }
private void TestServicesUrls() { KeyValueConfigurationCollection appSettings = GetServicesAppSettings(); bool allUrlOK = true; foreach (string key in appSettings.AllKeys) { string value = appSettings[key].Value; Uri uri; if (!Path.IsPathRooted(value) && Uri.TryCreate(value, UriKind.Absolute, out uri) && !string.IsNullOrEmpty(Path.GetExtension(value))) { // Got an URI, try hitting try { var client = _httpClientFactory.CreateClient(); var response = client.GetAsync(uri).Result; var result = response.Content.ReadAsStringAsync().Result; } catch (Exception x) { MarkAsFail(ServicesURLReachableLabel, x.Message, "Unreachable URL: " + key + "=" + uri.ToString()); allUrlOK = false; } } } if (allUrlOK) { MarkAsPass(ServicesURLReachableLabel); } }
/// <summary> /// install된 config파일에 새 값을 저장 /// 값이 다를 경우 config폴더에도 등록함. /// /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool SetValue(string key, string value) { try { Configuration exeConfig = GetExeConfig(); KeyValueConfigurationCollection exeConfigCollection = exeConfig.AppSettings.Settings; if (exeConfigCollection[key] != null) { exeConfigCollection[key].Value = value; } exeConfig.Save(ConfigurationSaveMode.Modified); Configuration backupConfig = GetBackupConfig(); if (!backupConfig.HasFile) { BackupConfig(); backupConfig = GetBackupConfig(); } KeyValueConfigurationCollection backupConfCollection = backupConfig.AppSettings.Settings; if (backupConfCollection[key] != null && !value.Equals(backupConfCollection[key].Value)) { backupConfCollection[key].Value = value; backupConfig.Save(ConfigurationSaveMode.Modified); } } catch (Exception ex) { Logger.error("SetValue중 에러:" + ex.ToString()); throw new Exception("SetValue중 에러"); } return(true); }
public void IsolateTheWebSettingSource() { _settingName = "Test"; _configuration = Isolate.Fake.Instance <Configuration>(); _settings = Isolate.Fake.Instance <KeyValueConfigurationCollection>(); // Note: have to fake the keyvalueconfiguration element, when actually creating it // using constructor(key, value), after creation element.key returns empty string??? var fakeElement = Isolate.Fake.Instance <KeyValueConfigurationElement>(); Isolate.WhenCalled(() => fakeElement.Key).WillReturn(_settingName); Isolate.WhenCalled(() => _settings[_settingName]).WillReturn(fakeElement); var empty = new[] { _settingName }; Isolate.WhenCalled(() => _settings.AllKeys).WillReturn(empty); _connections = Isolate.Fake.Instance <ConnectionStringSettingsCollection>(); var fakeConnection = Isolate.Fake.Instance <ConnectionStringSettings>(); Isolate.WhenCalled(() => fakeConnection.Name).WillReturn(_settingName); Isolate.WhenCalled(() => _connections[_settingName]).WillReturn(fakeConnection); Isolate.WhenCalled(() => _configuration.AppSettings.Settings).WillReturn(_settings); Isolate.WhenCalled(() => _configuration.ConnectionStrings.ConnectionStrings).WillReturn(_connections); _factory = Isolate.Fake.Instance <ConfigurationFactory>(); Isolate.WhenCalled(() => _factory.GetConfiguration()).WillReturn(_configuration); _configSettingSource = new ConfigurationSettingSource(_factory); }
public bool KeyExistsInCurrentConfig(string key) { Configuration exeConfig = GetExeConfig(); KeyValueConfigurationCollection exeConfigCollection = exeConfig.AppSettings.Settings; return(exeConfigCollection[key] != null); }
public static void Config(KeyValueConfigurationCollection config) { if (config["PLCIsCheck"] != null) { bIsCheck = DgiotHelper.StrTobool(config["PLCIsCheck"].Value); } }
/// <summary> /// backup된 config를 읽어 save된 정보를 /// 새로 install한 config에 저장한다. /// </summary> public void RecoverConfig() { Configuration backupConfig = GetBackupConfig(); KeyValueConfigurationCollection backupConfCollection = backupConfig.AppSettings.Settings; Configuration exeConfig = GetExeConfig(); KeyValueConfigurationCollection exeConfCollection = exeConfig.AppSettings.Settings; foreach (KeyValueConfigurationElement el in backupConfCollection) { string key = el.Key; string val = el.Value; if (exeConfCollection[key] == null) { continue; } string exeValue = exeConfCollection[key].Value; if (!val.Equals(exeValue)) { exeConfCollection[key].Value = val; Logger.info(string.Format("config 복구: old item[{0}][{1}]==> new item[{2}][{3}]" , key, val, key, exeValue)); } // do something with key and value } exeConfig.Save(ConfigurationSaveMode.Modified); //main config file에 반영한후 백업config로 overwrite BackupConfig(); }
private void LoadSyntaxHighlightingSettings(KeyValueConfigurationCollection appSettings) { LoadDefaultTokenHighlightSettings(appSettings); LoadKeywordTokenHighlightSettings(appSettings); LoadLiteralTokenHighlightSettings(appSettings); LoadCommentTokenHighlightSettings(appSettings); }
private void ReadConfig() { try { Configuration manager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection appSetting = manager.AppSettings.Settings; if (appSetting["keybind"] == null || appSetting["mean"] == null || appSetting["sigma"] == null || appSetting["clickOption"] == null) { InitConfig(); } Config.Instance.Key = (Key)int.Parse(appSetting["keybind"].Value); Config.Instance.Mean = double.Parse(appSetting["mean"].Value); Config.Instance.Sigma = double.Parse(appSetting["sigma"].Value); if (!appSetting["clickOption"].Value.Equals("left") && !appSetting["clickOption"].Value.Equals("right")) { throw new InvalidConstraintException("Invalid config value in clickOption"); } Config.Instance.LeftClick = appSetting["clickOption"].Value.Equals("left"); ((TextBox)this.FindName("Keybind")).Text = KeyUtil.ConvertKeyToString(Config.Instance.Key); ((TextBox)this.FindName("MeanTextBox")).Text = Config.Instance.Mean.ToString(CultureInfo.InvariantCulture); ((TextBox)this.FindName("SigmaTextBox")).Text = Config.Instance.Sigma.ToString(CultureInfo.InvariantCulture); ((ComboBox)this.FindName("ClickOption")).SelectedIndex = Config.Instance.LeftClick ? 0 : 1; } catch (Exception) { InitConfig(); } }
private static T CreateReflectionBasedMock <T>(KeyValueConfigurationCollection settingsCollection) where T : class, IEnvironmentInfoProvider { var mock = new Mock <T>(); var properties = typeof(T).GetProperties(); foreach (var keyName in settingsCollection.AllKeys) { var propertyInfo = properties.FirstOrDefault(e => string.Compare(e.Name, keyName, StringComparison.CurrentCultureIgnoreCase) == 0); if (propertyInfo == null) { continue; } //decrypt encrypted values string valueFromAppConfig = ReadAndDecryptValue(propertyInfo, settingsCollection[keyName].Value); if (propertyInfo.PropertyType.IsArray) { var getter = GetPropGetterExpression <T, string[]>(propertyInfo); mock.SetupGet(getter).Returns(valueFromAppConfig.Split(';')); } else { var getter = GetPropGetterExpression <T, string>(propertyInfo); mock.SetupGet(getter).Returns(valueFromAppConfig); } } return(mock.Object); }
protected void Page_Load(object sender, EventArgs e) { Response.Write("读取web.config配置文件中的连接字符串<br/>"); foreach (ConnectionStringSettings connection in WebConfigurationManager.ConnectionStrings) { Response.Write("连接名称: " + connection.Name + "<br />"); Response.Write("连接字符串: " + connection.ConnectionString + "<br /><br />"); ////返回位于网站根目下的配置对象 //Configuration config =WebConfigurationManager.OpenWebConfiguration("/"); //// 搜索位于<system.web>内部的 <authentication> 元素 //AuthenticationSection authSection = //(AuthenticationSection)config.GetSection(@"system.web/authentication"); //首先返回位于网站根目下的配置对象,必须注意这里的网站根目录虚拟路径用~/,而不要使用一个/号。 Configuration config = WebConfigurationManager.OpenWebConfiguration("~/") as System.Configuration.Configuration; KeyValueConfigurationCollection appSettings = config.AppSettings.Settings; if (config != null) { //在这里更改appSettings对象 appSettings["SiteName"].Value = "WebConfigurationManager类使用演示"; appSettings["FileName"].Value = "这是一个web.Config文件"; config.Save(); } Response.Write("读取web.config配置文件中的<appSettings>配置节<br/>"); foreach (string key in appSettings.AllKeys) { Response.Write("键值名: " + key + "<br />"); Response.Write("键值值为: " + appSettings[key].Value + "<br/><br/>"); } } }
/// <summary> /// Change the value for specified key /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void ChangeKeyValue(string key, string value, bool isConnectionString, bool isAppSetting) { if (isAppSetting) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); AppSettingsSection App_Section = (AppSettingsSection)config.GetSection("appSettings"); KeyValueConfigurationCollection app_settings = App_Section.Settings; KeyValueConfigurationElement element = app_settings[key]; if (element != null) { element.Value = value; app_settings.Remove(key); app_settings.Add(element); config.Save(ConfigurationSaveMode.Full, true); ConfigurationManager.RefreshSection("appSettings"); } } if (isConnectionString) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConnectionStringsSection connectionString_Section = (ConnectionStringsSection)config.GetSection("appSettings"); ConnectionStringSettingsCollection connectionString_settings = connectionString_Section.ConnectionStrings; ConnectionStringSettings element = connectionString_settings[key]; if (element != null) { element.ConnectionString = "blah"; connectionString_settings.Remove(key); connectionString_settings.Add(element); config.Save(ConfigurationSaveMode.Full, true); ConfigurationManager.RefreshSection("appSettings"); } } }
// </Snippet15> // <Snippet16> // Show how to use OpenWebConfiguration(string, string, string). // It gets he appSettings section of a Web application // runnig on the local server. static void OpenWebConfiguration3() { // Get the configuration object for a Web application // running on the local server. System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration( "/configTest", "Default Web Site", null) as System.Configuration.Configuration; // Get the appSettings. KeyValueConfigurationCollection appSettings = config.AppSettings.Settings; // Loop through the collection and // display the appSettings key, value pairs. Console.WriteLine( "[appSettings for app at: /configTest"); Console.WriteLine(" site: Default Web Site"); Console.WriteLine(" and locationSubPath: null]"); foreach (string key in appSettings.AllKeys) { Console.WriteLine("Name: {0} Value: {1}", key, appSettings[key].Value); } Console.WriteLine(); }