All notes
Configurati

Advanced architecture

MSDN: Application Settings Architecture.

Defining Settings

SettingsBase, which provides access to settings through a collection, and provides low-level methods for loading and saving settings.

Each environment implements its own class derived from SettingsBase to provide additional settings functionality for that environment.

ApplicationSettingsBase

In a Windows Forms-based application, all application settings must be defined on a class derived from the ApplicationSettingsBase class, which adds the following functionality to the base class:

The settings can be described using a number of attributes defined within the System.Configuration namespace, with either ApplicationScopedSettingAttribute or UserScopedSettingAttribute, which describes whether the setting applies to the entire application or just to the current user.


using System;
using System.Configuration;
using System.Drawing;

public class MyUserSettings : ApplicationSettingsBase
{
    [UserScopedSetting()]
    [DefaultSettingValue("white")]
    public Color BackgroundColor
    {
        get
        {
            return ((Color)this["BackgroundColor"]);
        }
        set
        {
            this["BackgroundColor"] = (Color)value;
        }
    }
}

Settings Persistence

The ApplicationSettingsBase class does not itself persist or load settings; this job falls to the settings provider, a class that derives from SettingsProvider. If a derived class of ApplicationSettingsBase does not specify a settings provider through the SettingsProviderAttribute, then the default provider, LocalFileSettingsProvider, is used.

LocalFileSettingsProvider

The configuration system that was originally released with the .NET Framework supports providing static application configuration data through either the local computer's machine.config file or within an app.exe.config file that you deploy with your application.

The LocalFileSettingsProvider class expands this native support in the following ways:

An app.exe.config file which contains both application-scoped settings and defaults for user-scoped settings would look like this:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="WindowsApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        </sectionGroup>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="WindowsApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" />
        </sectionGroup>
    </configSections>
    <applicationSettings>
        <WindowsApplication1.Properties.Settings>
            <setting name="Cursor" serializeAs="String">
                <value>Default</value>
            </setting>
            <setting name="DoubleBuffering" serializeAs="String">
                <value>False</value>
            </setting>
        </WindowsApplication1.Properties.Settings>
    </applicationSettings>
    <userSettings>
        <WindowsApplication1.Properties.Settings>
            <setting name="FormTitle" serializeAs="String">
                <value>Form1</value>
            </setting>
            <setting name="FormSize" serializeAs="String">
                <value>595, 536</value>
            </setting>
        </WindowsApplication1.Properties.Settings>
    </userSettings>
</configuration>

See MSDN: Application Settings Schema for details.

Settings File Locations

The location of the app.exe.config and user.config files will differ based on how the application is installed. For a Windows Forms-based application copied onto the local computer, app.exe.config will reside in the same directory as the base directory of the application's main executable file, and user.config will reside in the location specified by the Application.LocalUserAppDataPath property. For an application installed by means of ClickOnce, both of these files will reside in the ClickOnce Data Directory underneath %InstallRoot%\Documents and Settings\username\Local Settings.

The storage location of these files is slightly different if a user has enabled roaming profiles, which enables a user to define different Windows and application settings when he or she is using other computers within a domain. In that case, both ClickOnce applications and non-ClickOnce applications will have their app.exe.config and user.config files stored under %InstallRoot%\Documents and Settings\username\Application Data.

Custom Settings Providers

In the Application Settings architecture, there is a loose coupling between the applications settings wrapper class, derived from ApplicationSettingsBase, and the associated settings provider or providers, derived from SettingsProvider. This association is defined only by the SettingsProviderAttribute applied to the wrapper class or its individual properties. If a settings provider is not explicitly specified, the default provider, LocalFileSettingsProvider, is used. As a result, this architecture supports creating and using custom settings providers.

For example, suppose that you want to develop and use SqlSettingsProvider, a provider that will store all settings data in a Microsoft SQL Server database. Your SettingsProvider-derived class would receive this information in its Initialize method as a parameter of type System.Collections.Specialized.NameValueCollection. You would then implement the GetPropertyValues method to retrieve your settings from the data store, and SetPropertyValues to save them. Your provider can use the SettingsPropertyCollection supplied to GetPropertyValues to determine the property's name, type, and scope, as well as any other settings attributes defined for that property.

Library References

System.Configuration

MSDN: System.Configuration.

Represents a configuration file that is applicable to a particular computer, application, or resource.

Configuration settings are stored in a hierarchy of configuration files. The Configuration class instance represents the merged view of the configuration settings from all of the configuration files that apply to a specific physical entity, such as a computer, or to a logical entity, such as an application or a Web site.

When no configuration file exists for a specified entity, the Configuration object represents the default configuration settings as defined by the Machine.config file.

You can get a Configuration object by using the following classes:

You can also generate a configuration file that represents the configuration settings in a Configuration object, using Save() or SaveAs().

You use the GetSection method or the GetSectionGroup method to read configuration information. However, if your application needs read-only access to its own configuration, it is recommended that you use the ConfigurationManager.GetSection() method overloads, which provide access to the cached configuration values for the current application, which has better performance than the Configuration class.

ConnectionStrings


<connectionStrings>
  <add name="BlogContext"
        providerName="System.Data.SqlClient"
        connectionString="Server=.\SQLEXPRESS;Database=Blogging;Integrated Security=True;"/>
</connectionStrings>

Initial Catalog, database

Gets or sets the name of the database associated with the connection.

SO. These two can be used interchangeably. See the documentation of SqlConnectionStringBuilder.InitialCatalog, which marks:

This property corresponds to the "Initial Catalog" and "database" keys within the connection string.

Integrated Security

cnblog. integrated security=true 的意思是集成验证,也就是说使用Windows验证的方式去连接到数据库服务器。这样方式的好处是不需要在连接字符串中编写用户名和密码,从一定程度上说提高了安全性。

MSDN. If your application runs on a Windows-based intranet, you might be able to use Windows integrated authentication for database access.

You can supply a specific user name and password for the Web site's worker process identity (reference), or you can impersonate the authenticated identity supplied by Internet Information Services (IIS). To impersonate the Windows identity supplied by IIS, set the impersonate attribute of the identity configuration element to true as shown in the following example:


<system.web>
  <identity impersonate="true" />
</system.web>

AppSettings, ConnectionStrings

MSDN: appSettingsSection. MSDN: connectionStringsSection.


public sealed class AppSettingsSection : ConfigurationSection
public sealed class ConnectionStringsSection : ConfigurationSection

The appSettings configuration section provides for key/value pairs of string values for an application.

cnblogs: connectionStrings vs appSettings.

StackOverflow: connectionStrings vs appSettings.


<configuration>
    <connectionStrings>
        <add name="MyConnectionString" connectionString="..." />
    </connectionStrings>
</configuration>

<!-- -->

<configuration>
    <appSettings>
        <add key="MyConnectionString" value="..." />
    </appSettings>
</configuration>

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);

Example



using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Specialized;

#region CustomSection class

// Define a custom section. This class is used to populate the configuration file.
// It creates the following custom section:
//  <CustomSection name="Contoso" url="http://www.contoso.com" port="8080" />.
public sealed class CustomSection : ConfigurationSection
{

    public CustomSection()
    {}

    [ConfigurationProperty("name",
     DefaultValue = "Contoso",
     IsRequired = true,
     IsKey = true)]
    public string Name
    {
        get
        {
            return (string)this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }

    [ConfigurationProperty("url",
        DefaultValue = "http://www.contoso.com",
        IsRequired = true)]
    [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
    public string Url
    {
        get
        {
            return (string)this["url"];
        }
        set
        {
            this["url"] = value;
        }
    }

    [ConfigurationProperty("port",
        DefaultValue = (int)8080,
        IsRequired = false)]
    [IntegerValidator(MinValue = 0,
        MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }
}

#endregion

#region Using Configuration Class
class UsingConfigurationClass
{
    // Show how to create an instance of the Configuration class that represents this application configuration file.  
    static void CreateConfigurationFile()
    {
        try
        {
            CustomSection customSection = new CustomSection();

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Create the custom section entry in <configSections> group and the related target section in <configuration>.
            if (config.Sections["CustomSection"] == null)
            {
                config.Sections.Add("CustomSection", customSection);
            }

            // Create and add an entry to appSettings section.

            string conStringname="LocalSqlServer";
            string conString = @"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true";
            string providerName="System.Data.SqlClient";

            ConnectionStringSettings connStrSettings = new ConnectionStringSettings();
            connStrSettings.Name = conStringname;
            connStrSettings.ConnectionString= conString;
            connStrSettings.ProviderName = providerName;

            config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);

            // Add an entry to appSettings section.
            int appStgCnt = ConfigurationManager.AppSettings.Count;
            string newKey = "NewKey" + appStgCnt.ToString();
            string newValue = DateTime.Now.ToLongDateString() +
              " " + DateTime.Now.ToLongTimeString();
            config.AppSettings.Settings.Add(newKey, newValue);

            // Save the configuration file.
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);

            Console.WriteLine("Created configuration file: {0}",
                config.FilePath);

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateConfigurationFile: {0}", err.ToString());
        }

    }

    // Show how to use the GetSection(string) method.
    static void GetCustomSection()
    {
        try
        {
            CustomSection customSection;

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            customSection =
                config.GetSection("CustomSection") as CustomSection;

            Console.WriteLine("Section name: {0}", customSection.Name);
            Console.WriteLine("Url: {0}", customSection.Url);
            Console.WriteLine("Port: {0}", customSection.Port);

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("Using GetSection(string): {0}", err.ToString());
        }

    }


    // Show how to use different modalities to save a configuration file.
    static void SaveConfigurationFile()
    {
        try
        {
            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Save the full configuration file and force save even if the file was not modified.
            config.SaveAs("MyConfigFull.config", ConfigurationSaveMode.Full, true);
            Console.WriteLine("Saved config file as MyConfigFull.config using the mode: {0}",
                ConfigurationSaveMode.Full.ToString());

            config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Save only the part of the configuration file that was modified. 
            config.SaveAs("MyConfigModified.config", ConfigurationSaveMode.Modified, true);
            Console.WriteLine("Saved config file as MyConfigModified.config using the mode: {0}",
                ConfigurationSaveMode.Modified.ToString());

            config = ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Save the full configuration file.
            config.SaveAs("MyConfigMinimal.config");
            Console.WriteLine("Saved config file as MyConfigMinimal.config using the mode: {0}",
                ConfigurationSaveMode.Minimal.ToString());

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("SaveConfigurationFile: {0}", err.ToString());
        }

    }

    // Show how use the AppSettings and ConnectionStrings properties.
    static void GetSections(string section)
    {
        try
        {
            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Get the selected section.
            switch (section)
            {
                case "appSettings":
                    try
                    {
                        AppSettingsSection appSettings =
                            config.AppSettings as AppSettingsSection;
                        Console.WriteLine("Section name: {0}",
                                appSettings.SectionInformation.SectionName);

                        // Get the AppSettings section elements.
                        Console.WriteLine();
                        Console.WriteLine("Using AppSettings property.");
                        Console.WriteLine("Application settings:");
                        // Get the KeyValueConfigurationCollection 
                        // from the configuration.
                        KeyValueConfigurationCollection settings =
                          config.AppSettings.Settings;

                        // Display each KeyValueConfigurationElement.
                        foreach (KeyValueConfigurationElement keyValueElement in settings)
                        {
                            Console.WriteLine("Key: {0}", keyValueElement.Key);
                            Console.WriteLine("Value: {0}", keyValueElement.Value);
                            Console.WriteLine();
                        }
                    }
                    catch (ConfigurationErrorsException e)
                    {
                        Console.WriteLine("Using AppSettings property: {0}",
                            e.ToString());
                    }
                    break;

                case "connectionStrings":
                    ConnectionStringsSection
                        conStrSection =
                        config.ConnectionStrings as ConnectionStringsSection;
                    Console.WriteLine("Section name: {0}",
                        conStrSection.SectionInformation.SectionName);

                    try
                    {
                        if (conStrSection.ConnectionStrings.Count != 0)
                        {
                            Console.WriteLine();
                            Console.WriteLine("Using ConnectionStrings property.");
                            Console.WriteLine("Connection strings:");

                            // Get the collection elements.
                            foreach (ConnectionStringSettings connection in
                              conStrSection.ConnectionStrings)
                            {
                                string name = connection.Name;
                                string provider = connection.ProviderName;
                                string connectionString = connection.ConnectionString;

                                Console.WriteLine("Name:               {0}",
                                  name);
                                Console.WriteLine("Connection string:  {0}",
                                  connectionString);
                                Console.WriteLine("Provider:            {0}",
                                   provider);
                            }
                        }
                    }
                    catch (ConfigurationErrorsException e)
                    {
                        Console.WriteLine("Using ConnectionStrings property: {0}",
                            e.ToString());
                    }
                    break;

                default:
                    Console.WriteLine(
                        "GetSections: Unknown section (0)", section);
                    break;
            }

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetSections: (0)", err.ToString());
        }
    }

    // Show how to use the Configuration object properties 
    // to obtain configuration file information.
    static void GetConfigurationInformation()
    {
        try
        {
            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            Console.WriteLine("Reading configuration information:");

            ContextInformation evalContext =
                config.EvaluationContext as ContextInformation;
            Console.WriteLine("Machine level: {0}",
                evalContext.IsMachineLevel.ToString());

            string filePath = config.FilePath;
            Console.WriteLine("File path: {0}", filePath);

            bool hasFile = config.HasFile;
            Console.WriteLine("Has file: {0}", hasFile.ToString());


            ConfigurationSectionGroupCollection
                groups = config.SectionGroups;
            Console.WriteLine("Groups: {0}", groups.Count.ToString());
            foreach (ConfigurationSectionGroup group in groups)
            {
                Console.WriteLine("Group Name: {0}", group.Name);
               // Console.WriteLine("Group Type: {0}", group.Type);
            }

            ConfigurationSectionCollection
                sections = config.Sections;
            Console.WriteLine("Sections: {0}", sections.Count.ToString());

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetConfigurationInformation: {0}",err.ToString());
        }
    }

#endregion 

#region Application Main
    //*** User Interaction Class ***//

    // Obtain user's input and provide feedback.
    // This class contains the application Main() function.
    // It calls the ConfigurationManager methods based 
    // on the user's selection.
    class ApplicationMain
    {
        // Display user's menu.
        public static void UserMenu()
        {
            string applicationName =
                Environment.GetCommandLineArgs()[0] + ".exe";
            StringBuilder buffer = new StringBuilder();

            buffer.AppendLine("Application: " + applicationName);
            buffer.AppendLine("Make your selection.");
            buffer.AppendLine("?    -- Display help.");
            buffer.AppendLine("Q,q  -- Exit the application.");

            buffer.Append("1    -- Instantiate the");
            buffer.AppendLine(" Configuration class.");

            buffer.Append("2    -- Use GetSection(string) to read ");
            buffer.AppendLine(" a custom section.");

            buffer.Append("3    -- Use SaveAs methods");
            buffer.AppendLine(" to save the configuration file.");

            buffer.Append("4    -- Use AppSettings property to read");
            buffer.AppendLine(" the appSettings section.");
            buffer.Append("5    -- Use ConnectionStrings property to read");
            buffer.AppendLine(" the connectionStrings section.");

            buffer.Append("6    -- Use Configuration class properties");
            buffer.AppendLine(" to obtain configuration information.");

            Console.Write(buffer.ToString());
        }

        // Obtain user's input and provide
        // feedback.
        static void Main(string[] args)
        {
            // Define user selection string.
            string selection;

            // Get the name of the application.
            string appName = Environment.GetCommandLineArgs()[0];

            // Get user selection.
            while (true)
            {

                UserMenu();
                Console.Write("> ");
                selection = Console.ReadLine();
                if (selection != string.Empty)
                    break;
            }

            while (selection.ToLower() != "q")
            {
                // Process user's input.
                switch (selection)
                {
                    case "1":
                        // Show how to create an instance of the Configuration class.
                        CreateConfigurationFile();
                        break;

                    case "2":
                        // Show how to use GetSection(string) method.
                        GetCustomSection();
                        break;

                    case "3":
                        // Show how to use ConnectionStrings.
                        SaveConfigurationFile();
                        break;

                    case "4":
                        // Show how to use the AppSettings property.
                        GetSections("appSettings");
                        break;

                    case "5":
                        // Show how to use the ConnectionStrings property.
                        GetSections("connectionStrings");
                        break;

                    case "6":
                        // Show how to obtain configuration file information.
                        GetConfigurationInformation();
                        break;

                    default:
                        UserMenu();
                        break;
                }
                Console.Write("> ");
                selection = Console.ReadLine();
            }
        }
    }
#endregion

}

System.ConfigurationManager

OpenExeConfiguration()

MSDN: OpenExeConfiguration.

Opens the configuration file for the current application as a Configuration object.

Param: UserLevel


public static Configuration OpenExeConfiguration(
	ConfigurationUserLevel userLevel
)

Client applications use a global configuration that applies to all users, separate configurations that apply to individual users, and configurations that apply to roaming users. Specify which configuration to get by passing one of the following values for userLevel:

SO: get the location of the user config file. We can see the difference between these userLevels in the following example:


using System.Configuration;

public static class Test
{
    public static void Main()
    {
        System.Console.WriteLine(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
        System.Console.WriteLine(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming).FilePath);
        System.Console.WriteLine(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath);
    }
}

// C:\Users\me\Desktop\test.exe.Config
// C:\Users\me\AppData\Roaming\Test\test.exe_Url_hkxqpncuiskqilpz02trla1fozam13d3\0.0.0.0\user.config
// C:\Users\me\AppData\Local\Test\test.exe_Url_hkxqpncuiskqilpz02trla1fozam13d3\0.0.0.0\user.config

Microsoft technet: AppData local vs roaming. The user data placed in the "AppData\Roaming" folder is used for User Profile specific data, while the "AppData\Local" folder structure is used for Machine Specific data.

Param: String

MSDN.


public static Configuration OpenExeConfiguration(
	string exePath // The path of the executable (exe) file.
)

using System;
using System.Configuration;

public static class Test
{
    public static void Main()
    {
        string applicationName = Environment.GetCommandLineArgs()[0];
        string exePath = System.IO.Path.Combine(Environment.CurrentDirectory, applicationName);
        System.Console.WriteLine(ConfigurationManager.OpenExeConfiguration(exePath).FilePath);
    }
}

// c:\Users\me\Desktop\test.exe.config

GetSection()

The GetSection method accesses run-time configuration information that it cannot change. To change the configuration, you use the GetSection method on the configuration file that you obtain, e.g. by OpenExeConfiguration().

Recommended way. You must cast the return value to the expected configuration type. To avoid possible casting exceptions, you should use a conditional casting operation such as the as operator in C#.

Read from app.config

MSDN.


<appSettings>
    <add key="AppId" value="123"/>
    <add key="AppSecret" value="secret"/>
</appSettings>

static void readConfig()
{
    var appSettings = ConfigurationSettings.AppSettings;
    try
    {
        appid = appSettings["AppId"] ?? "NotExist"; // wcfNote: ?? is an interesting good operator.
        secret = appSettings["AppSecret"] ?? "NotExist";
        Console.WriteLine(string.Format("ID and Secret: {0}, {1}.", appid, secret));
    }
    catch (Exception e)
    {
        Console.WriteLine(Utilities.Utilities.printExceptionRecursively(e));
    }
}

Properties.Settings

The project system stores application settings in two XML files:

You can change the type of a setting by using the Scope property.

Notice that changes in user settings are not written to disk unless the application specifically calls a method to do this.

Creating Application Settings at Design Time

At design time, you can create application settings in two ways:

When you create an application-scoped setting (for example, a database connection string, or a reference to server resources), Visual Studio saves it in app.config with the "applicationSettings" tag. (Connection strings are saved under the "connectionStrings" tag.)

When you create a user-scoped setting (for example, default font, home page, or window size), Visual Studio saves it in app.config with the "userSettings" tag.

Customized Settings file

The Settings Designer first searches for the Settings.settings file that the project system creates; this is the default file that the Project Designer displays in the Settings tab. Settings.settings is located in the My Project folder for Visual Basic projects and in the Properties folder for Visual C# projects.

The Project Designer then searches for other settings files in the project's root folder. Therefore, you should put your custom settings file there.

Accessing or Changing Application Settings at Run Time in Visual C#

In Visual C#, you must access the Settings class directly, as shown in the following Visual C# example.

You must also explicitly call the Save method of this wrapper class in order to persist the user settings. You usually do this in the Closing event handler of the main form.


// wcfNote: The "Settings.Default" is a property returning a settings singleton.
Properties.Settings.Default.logOutput = false;
Properties.Settings.Default.Save();

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="UnitTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <userSettings>
        <UnitTest.Properties.Settings>
            <setting name="logOutput" serializeAs="String">
                <value>False</value>
            </setting>
        </UnitTest.Properties.Settings>
    </userSettings>
</configuration>

FAQ: Reload doesnot work in Debug

MSDN: Properties.Default.Reload() fails in debug mode.

Since the .Net code is hosted in the TestProps.vshost.exe process, the Reload() method will try to find TestProps.vshost.exe.config file which does not exist. That's why our modification to testprops.exe.config will take no effect in debugging mode.

Settings.settings vs. app.config

SO: settings.settings vs app.config.

You can use the XML app.config file, adding items to the "appSettings" section. These can be retrieved from code using the ConfigurationManager class.

Alternatively, you can use the Settings.settings file (also XML) to add individual settings through an editor. Visual Studio will generate a Settings class for type-safe retrieval of settings at run-time.

The settings API offers read/write access from the application, whereas config is read only (unless you write the file in code).

App.config is per application only. Changes to App.config aren't automatically picked up. It requires restart or code to refresh the values.

You could use Settings in a desktop application for storing user preferences, or settings that change at runtime. You would use App.config for more generic static settings, like connection strings etc, or for defining the configuration of components used within your app.

Settings.settings

MSDN: Using Settings in C#.

To Create a New Setting at Design Time: In Solution Explorer, expand the Properties node of your project. In Solution Explorer, double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings.


// Read in a value from the Setting.settings file
inputBox.Text = Properties.Settings.Default.SavedInputString;

void TextWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    // We are going to write to the settings in our code. We take the results
    // of a function, and set the settings string equal to it.
    //
    Properties.Settings.Default.SavedInputString = SanitizeInput(inputBox.Text);

    // Now, we need to save the settings file. If we don't save it, they disappear.
    Properties.Settings.Default.Save();
}