[ACCEPTED]-How do I retrieve ApplicationSettings from a loaded App.config file?-application-settings

Accepted answer
Score: 16

The applicationSettings are readonly during runtime. You can set/modify 91 them either via a text editor in the app.config 90 file directly, but it is recommended to 89 open the project properties in Visual Studio 88 and select the "Settings" tab. It 87 is important to set the right scope:

  • If the settings apply to the entire application (for all users), select "Application" as scope.
  • If every user should have individual settings (bound to the user profile), then select "User"

For 86 example, if you create myOwnSetting in your project 85 WindowsFormsTestApplication1 as follows (change the scope to "Application"):

myOwnSetting

it will 84 add the following to the application's app.config 83 file:

<configuration>
    <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <section name="WindowsFormsTestApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
    </configSections>
    <applicationSettings>
        <WindowsFormsTestApplication1.Properties.Settings>
            <setting name="myOwnSetting" serializeAs="String">
                <value>Hi there!</value>
            </setting>
        </WindowsFormsTestApplication1.Properties.Settings>
    </applicationSettings>
</configuration>

Visual Studio creates C# code to access 82 this setting automatically (this is why 81 you should do it in the project properties 80 and not via text editor) - after you have 79 saved the changes, from within the same 78 namespace you can read its value in the 77 application easily via the following code:

var currentValue = Properties.Settings.Default.myOwnSetting;

Given 76 the applicationSettings in the listing above, this would retrieve 75 the string "Hi there!" for the 74 variable currentValue.

Note that if you have created myOwnSetting for 73 the "User" scope, then it is stored in a section named 72 <userSettings> instead of <applicationSettings>, but you still can access it 71 with the code line above.

Another difference 70 of scope "User" settings is that you have read-write 69 access, i.e. it is allowed to do the following:

        Properties.Settings.Default.myUserSetting = "Something else";
        Properties.Settings.Default.Save();

If 68 you try the same with the "Application" scope 67 setting myOwnSetting, it would result in 66 a compile-time error telling you that it 65 is read-only.

If you re-start the application, you 64 will notice that myUserSetting has changed 63 to the value "Something else" - but 62 the old value is still in the app.config. Why 61 is this so? The reason is that it is regarded 60 as a default value - and as I said earlier, the 59 "User" scope is bound to the user 58 profile. As a consequence, the value "Something 57 else" is stored in

C:\Documents and Settings\USERID\Local Settings\Application Data\FIRMNAME\WindowsFormsTestApplicati_Url_tdq2oylz33rzq00sxhvxucu5edw2oghw\1.0.0.0

in a file named User.config, which 56 looks as follows:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <WindowsFormsTestApplication1.Properties.Settings>
            <setting name="myUserSetting" serializeAs="String">
                <value>Something else</value>
            </setting>
        </WindowsFormsTestApplication1.Properties.Settings>
    </userSettings>
</configuration>

You can't exactly tell 55 the path as it is created automatically 54 by the .NET Framework, and it will look 53 different on your PC. But you can see that 52 USERID is the Windows user ID of your current 51 user, FIRMNAME is part of the assembly information 50 you have specified, and the assembly name 49 and version is also used in the path.


Note:

  • The 48 <sectionGroup> with <section> declaration is mandatory and its 47 name attribute needs to match with the namespace. The 46 namespace must appear exactly once in the 45 configuration, and there is only one applicationSettings section 44 allowed.

  • As you could see in the config file, the 43 namespace is mentioned explicitly there 42 (WindowsFormsTestApplication1.Properties.Settings). As a consequence, if you want to access 41 the settings from code not being in the 40 same namespace you might need to use a fully 39 qualified reference. Having said that, be 38 careful if you copy the entire <applicationSettings>...</applicationSettings> section 37 from one application's config to another 36 - you might need to change the namespace 35 in the target config afterwards.

  • If you're 34 using the Settings Designer (Settings tab 33 in your project), it will create a file 32 named Settings.Settings (along with Settings.Designer.cs to access the sessings 31 via C# code) in the Properties section of 30 your project. This is a copy of the settings 29 as it will be stored in your Web.config or App.config file as 28 well (depending on your project type, only 27 for application scope settings - user scope 26 settings are stored based on the user profile). You 25 can create additional *.settings files and use them 24 (as it is described here).

  • If you're not using the 23 settings designer, or if you're using a 22 tool like LinqPad, you might need to use a different 21 approach. Consider this:

    internal static string GetApplicationSetting(string key, 
            string nameSpace="Properties.Settings")
    {
        string xValue=null;
        try 
        {
            string path = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            XDocument doc = XDocument.Load(path);
            var xPathStr= string.IsNullOrEmpty(nameSpace) 
                            ? "//applicationSettings" 
                            : $"//applicationSettings/{nameSpace}";
            var settings=doc.XPathSelectElement(xPathStr).Elements().Where(
                                w => w.Name=="setting" 
                                    && w.HasAttributes 
                                    && w.Attribute("serializeAs").Value=="String"
                                );
            var setting=settings.Where(f => f.HasAttributes 
                                            && f.Attribute("name").Value==key).Elements();
            xValue=setting.FirstOrDefault().Value;
        }
        catch {}
        return xValue;
    }
    

    You can read string 20 type applicationSettings by treating the configuration as an 19 XDocument. The example given is limited to the string 18 type and you can retrieve the setting from 17 the app.config example above as follows:
    var value=GetApplicationSetting("myOwnSetting", "WindowsFormsTestApplication1.Properties.Settings");
    Likewise, you 16 can create a similar function GetUserSetting for the default 15 <userSettings> section: Just copy the code above, rename 14 the function name and replace applicationSettings in the xPathStr by 13 userSettings.

  • There is an upgrade method available for 12 user settings, which is described here. More 11 details about the location where user settings 10 are stored can be found there.

  • The <appSettings> section in 9 the configuration works differently, since 8 it does not distinguish "User" and 7 "Application" scope and it does 6 not support different datatypes, just strings. However, it 5 is possible to easily read and write the configuration 4 keys/values. If you're interested in the 3 code, you can find it here (on stackoverflow):
    how to read/write config settings of appSettings

  • If 2 you are uncertain whether you should use 1 AppSettings or applicationSettings, then read this before you decide it.

Score: 4

How did you create the settings? Using 10 the VS settings designer? If so it should 9 create you a strongly typed class for accessing 8 them with. This is usually accessed using 7 Properties.Settings.Default.SettingName

I think that it is preferred to use the 6 applicationSettings rather than appSettings, but 5 application settings are readonly at runtime, ie 4 you cannot create them from your code, but 3 it is possible to create and add appSettings 2 at runtime I believe. I asked a question about the difference

you can find more 1 information from msdn

Score: 3
You could load the config file into XmlDocument and retrive the applicationSettings from the dom object . Here is example I found to load the config file into dom object :

//retrive the current assembly directory
private static string AssemblyDirectory()
{
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
}



//return the value from aplicationSetting according to the given key
//appSettingSection is the your configuration section as declare in your web.config
public static string GetApplicationSettingValue(string appSettingSection,string key)
{
   //get web.config path
   string configPath  = new System.IO.DirectoryInfo(AssemblyDirectory()).Parent.FullName + "\\web.config";

    System.IO.FileInfo FileInfo = new System.IO.FileInfo(configPath);
    if (!FileInfo.Exists)
    {
        throw new Exception("Missing config file");
    }

    //load config file into xml document
    var XmlConfig = new System.Xml.XmlDocument();
    XmlConfig.Load(FileInfo.FullName);


     //override xml document and return the value of the key under applicationSettings
     foreach (System.Xml.XmlNode node in XmlConfig["configuration"]  ["applicationSettings"]appSettingSection])
     {
                    if (node.Name == "setting")
                    {
                        if (node.Attributes.GetNamedItem("name").Value == key)
                        {
                            return node.FirstChild.InnerXml.ToString();
                        }
                   }
     }
   return "";
}

0

More Related questions