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

发布于 2024-08-18 03:48:40 字数 306 浏览 5 评论 0原文

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

我找到了一个示例如何检索 appSettings,但我不知道如何以这种方式访问​​applicationSettings

Is it possible to access the values from the applicationSettings section of a loaded app.config file?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

乞讨 2024-08-25 03:48:40

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

  • 如果设置适用于整个应用程序(对于所有用户),请选择“应用程序”作为范围。
  • 如果每个用户都应该有单独的设置(绑定到用户配置文件),则选择“用户”。

例如,如果您在项目 WindowsFormsTestApplication1 中创建 myOwnSetting,如下所示(更改范围到“应用程序”):

myOwnSetting

它将添加以下内容到应用程序的 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 创建 C# 代码来自动访问此设置(这就是您应该这样做的原因在项目属性中而不是通过文本编辑器) - 保存更改后,在同一命名空间内,您可以通过以下代码轻松读取应用程序中的值:

var currentValue = Properties.Settings.Default.myOwnSetting;

给定列表中的 applicationSettings上面,这将检索字符串“Hi There!”对于变量currentValue

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

范围“用户”设置的另一个区别是您具有读写访问权限,即允许执行以下操作:

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

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

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

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

名为 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>

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


注意:

  • 带有

    声明的 是强制性的,其 name 属性需要与命名空间匹配。命名空间必须在配置中出现一次,并且只允许有一个 applicationSettings 部分。

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

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

  • 如果您使用设置设计器,或者使用LinqPad,您可能需要使用不同的方法。考虑一下:

     内部静态字符串 GetApplicationSetting(string key, 
              字符串 nameSpace="属性.设置")
      {
          字符串 xValue=null;
          尝试 
          {
              字符串路径= AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
              XDocument doc = XDocument.Load(路径);
              var xPathStr= string.IsNullOrEmpty(nameSpace) 
                              ? “//应用程序设置” 
                              : $"//applicationSettings/{nameSpace}";
              var settings=doc.XPathSelectElement(xPathStr).Elements().Where(
                                  w => w.Name=="设置" 
                                      && w.HasAttributes 
                                      && w.Attribute("serializeAs").Value=="String"
                                  );
              var 设置=settings.Where(f => f.HasAttributes 
                                              && f.Attribute("name").Value==key).Elements();
              xValue=setting.FirstOrDefault().Value;
          }
          抓住 {}
          返回x值;
      }
    

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

  • 有一种可用于用户设置的升级方法,此处对此进行了描述。有关用户设置存储位置的更多详细信息,请参阅那里

  • 如果该实现对于您的需求来说太复杂,则还有第二种实现设置的方法:配置中的 部分的工作方式有所不同,因为它不区分“用户”和“应用程序”范围,并且不支持不同的数据类型,仅支持字符串。但是,可以轻松读取和写入配置键/值。
    如果您对代码感兴趣,可以在这里找到它(在 stackoverflow 上):
    如何读取/写入appSettings的配置设置

重要:

  • 如果您不确定是否应该使用 appSettings 还是 applicationSettings,然后阅读在你决定之前。它比较了两种方式,显示了它们的优点和缺点。

The applicationSettings are readonly during 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:

  • 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 myOwnSetting in your project WindowsFormsTestApplication1 as follows (change the scope to "Application"):

myOwnSetting

it will add the following to the application's app.config 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 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:

var currentValue = Properties.Settings.Default.myOwnSetting;

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

Note that if you have created myOwnSetting for 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.

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.

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

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

in a file named User.config, which 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 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.


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 applicationSettings section 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.cs to 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.config or App.config file 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 *.settings files and use them (as it is described here).

  • If you're not using 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" 
                              : 
    quot;//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 applicationSettings by 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 GetUserSetting for the default <userSettings> section: Just copy the code above, rename the function name and replace applicationSettings in the xPathStr by 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.

  • If that implementation is too complicated for your needs, there is a second way to implement settings: 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 write the 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

Important:

  • If you are uncertain whether you should use appSettings or applicationSettings, then read this before you decide it. It compares both ways showing their advantages and disadvantages.
不可一世的女人 2024-08-25 03:48:40

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

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

您可以找到更多信息来自 msdn

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

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

you can find more information from msdn

哭泣的笑容 2024-08-25 03:48:40

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

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 "";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文