.net 如何从加载的 App.config 文件中检索 ApplicationSettings?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2101273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:49:20  来源:igfitidea点击:

How do I retrieve ApplicationSettings from a loaded App.config file?

.netvisual-studioconfigurationapp-configapplication-settings

提问by al-bex

Is it possible to access the values from the applicationSettingssection of a loaded app.configfile?

是否可以从applicationSettings加载的app.config文件的部分访问值?

I have found an example How do I retrieve appSettings, but I can't find out how to access applicationSettingsthis way.

我找到了一个示例How do I retrieve appSettings,但我不知道如何以applicationSettings这种方式访问。

回答by Matt

The applicationSettingsare readonlyduring runtime. You can set/modify them either via a text editor in the app.config file directly, but it is recommended to open the project properties in Visual Studio and select the "Settings" tab. It is important to set the right scope:

的applicationSettings只读的运行时。您可以通过 app.config 文件中的文本编辑器直接设置/修改它们,但建议在 Visual Studio 中打开项目属性并选择“设置”选项卡。设置正确的范围很重要:

  • 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 example, if you create myOwnSettingin your project WindowsFormsTestApplication1as follows (change the scope to "Application"):

例如,如果您在项目WindowsFormsTestApplication1 中创建myOwnSetting如下(将范围更改为"Application"):

myOwnSetting

我自己的设置

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

它会将以下内容添加到应用程序的 app.config 文件中:

<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 this setting automatically (this is why you should do it in the project properties and not via text editor) - after you have saved the changes, from within the same namespace you can read its value in the application easily via the following code:

Visual Studio 创建 C# 代码以自动访问此设置(这就是为什么您应该在项目属性中而不是通过文本编辑器执行此操作) - 保存更改后,在同一命名空间中,您可以轻松地在应用程序中读取其值通过以下代码:

var currentValue = Properties.Settings.Default.myOwnSetting;

Given the applicationSettingsin the listing above, this would retrieve the string "Hi there!" for the variable currentValue.

鉴于applicationSettings上面列表中的 ,这将检索字符串“Hi there!” 为变量currentValue

Notethat if you have created myOwnSettingfor the "User" scope, then it is stored in a section named <userSettings>instead of <applicationSettings>, but you still can access it with the code line above.

请注意,如果您已为“用户”范围创建了myOwnSetting,则它存储在名为而不是 的部分中,但您仍然可以使用上面的代码行访问它。<userSettings><applicationSettings>

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

范围“用户”设置的另一个不同之处在于您具有读写访问权限,即允许执行以下操作:

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

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

如果您对“应用程序”范围设置 myOwnSetting 进行相同尝试,则会导致编译时错误,告诉您它是只读的。

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

如果您重新启动应用程序,您会注意到 myUserSetting 已更改为值“其他” - 但旧值仍在 app.config 中。为什么会这样?原因是它被视为默认值 - 正如我之前所说,“用户”范围绑定到用户配置文件。因此,值“其他东西”存储在

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

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

在名为 的文件中User.config,如下所示:

<?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 the path as it is created automatically by the .NET Framework, and it will look different on your PC. But you can see that USERID is the Windows user ID of your current user, FIRMNAME is part of the assembly information you have specified, and the assembly name and version is also used in the path.

您无法准确说出路径,因为它是由 .NET Framework 自动创建的,并且在您的 PC 上看起来会有所不同。但是可以看到USERID是你当前用户的Windows用户ID,FIRMNAME是你指定的程序集信息的一部分,路径中也使用了程序集名称和版本。



Note:

笔记:

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

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

  • If you're using the Settings Designer (Settings tab in your project), it will create a file named Settings.Settings(along with Settings.Designer.csto access the sessings via C# code) in the Properties section of your project. This is a copy of the settings as it will be stored in your Web.configor App.configfile as well (depending on your project type, only for application scope settings - user scope settings are stored based on the user profile). You can create additional *.settingsfiles and use them (as it is described here).

  • If you're notusing the settings designer, or if you're using a tool like LinqPad, you might need to use a different 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 type applicationSettingsby treating the configuration as an XDocument. The example given is limited to the string type and you can retrieve the setting from the app.config example above as follows:
    var value=GetApplicationSetting("myOwnSetting", "WindowsFormsTestApplication1.Properties.Settings");
    Likewise, you can create a similar function GetUserSettingfor the default <userSettings>section: Just copy the code above, rename the function name and replace applicationSettingsin the xPathStrby userSettings.

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

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

  • If you are uncertain whether you should use AppSettingsor applicationSettings, then read thisbefore you decide it.

  • <sectionGroup><section>声明是强制性的,它的名字属性需要匹配的命名空间。命名空间必须在配置中只出现一次,并且只applicationSettings允许出现一个部分。

  • 正如您在配置文件中看到的,命名空间在 ( WindowsFormsTestApplication1.Properties.Settings) 中被明确提及。因此,如果您想从不在同一命名空间中的代码访问设置,您可能需要使用完全限定的引用。话虽如此,如果您将整个<applicationSettings>...</applicationSettings>部分从一个应用程序的配置复制到另一个应用程序的配置中,请小心- 之后您可能需要更改目标配置中的命名空间。

  • 如果您使用的是设置设计器(项目中的“设置”选项卡),它将在项目的“属性”部分创建一个名为Settings.Settings(以及Settings.Designer.cs通过 C# 代码访问 sessing)的文件。这是设置的副本,因为它也将存储在您的Web.configApp.config文件中(取决于您的项目类型,仅适用于应用程序范围设置 - 用户范围设置基于用户配置文件存储)。您可以创建其他*.settings文件,并使用它们(因为它是描述在这里)。

  • 如果您没有使用设置设计器,或者您使用的是LinqPad 之类的工具,则可能需要使用不同的方法。考虑一下:

    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;
    }
    

    您可以applicationSettings通过将配置视为XDocument. 给出的示例仅限于字符串类型,您可以从上面的 app.config 示例中检索设置,如下所示:
    var value=GetApplicationSetting("myOwnSetting", "WindowsFormsTestApplication1.Properties.Settings");
    同样,您可以为默认部分创建一个类似的函数GetUserSetting<userSettings>:只需复制上面的代码,重命名函数名称并applicationSettingsxPathStrby 中替换userSettings

  • 有一种可用于用户设置的升级方法,在此处进行描述。可以在此处找到有关存储用户设置的位置的更多详细信息。

  • <appSettings>配置中的部分的工作方式不同,因为它不区分“用户”和“应用程序”范围,也不支持不同的数据类型,只支持字符串。但是,可以轻松读取和写入配置键/值。如果您对代码感兴趣,可以在此处(在 stackoverflow 上)找到它:
    如何读/写 appSettings 的配置设置

  • 如果您不确定是否应该使用AppSettingsapplicationSettings在决定之前阅读此内容。

回答by Sam Holder

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

你是如何创建设置的?使用 VS 设置设计器?如果是这样,它应该为您创建一个用于访问它们的强类型类。这通常使用Properties.Settings.Default.SettingName

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

我认为最好使用 applicationSettings 而不是 appSettings,但应用程序设置在运行时是只读的,即您不能从代码中创建它们,但我相信可以在运行时创建和添加 appSettings。 我问了一个关于区别的问题

you can find more information from msdn

您可以从 msdn 中找到更多信息

回答by golan

您可以将配置文件加载到 XmlDocument 中并从 dom 对象中检索 applicationSettings。这是我发现将配置文件加载到 dom 对象的示例:

//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 "";
}