在web.config或app.config中存储分层应用设置

9

我需要将应用程序配置设置以分层格式存储在web.config或app.config中。这是否可行?还是我必须将其存储在某个XML文件或数据库中并使用它?对我来说,普通的名称值对格式不够。

    <appSettings>
        <Report1>
          <add key="SourceFilePath" value="value1" />
          <add key="DestinationFolderPath" value="value2" />
        </Report1>
        <Report2>
          <add key="SourceFilePath" value="value1" />
          <add key="DestinationFolderPath" value="value2" />
        </Report2>
   </appSettings>

这是一个基于网络的报告应用程序,我需要存储源文件、SSIS(SQL Server Integration Services)包、FTP服务器详细信息等的文件路径。

更新:如果我选择自定义配置部分选项,我能否将设置存储在单独的文件中,以便使主要的web.config文件干净无杂?


http://msdn.microsoft.com/en-us/library/2tw134k3.aspx - Jahan Zinedine
或者 http://www.google.com/search?q=ConfigurationSection - Jahan Zinedine
请返回已翻译的文本。 - Alper Ebicoglu
4个回答

6
您无法向appSettings添加自定义元素。
实现自定义格式的最佳方法是编写自己的ConfigurationSettings类并在配置中使用它。
这样可以让您以强类型的方式存储数据,并具有有意义的元素和属性名称。
请参见MSDN上的如何使用ConfigurationSection创建自定义配置节

谢谢。看起来我需要写很多代码。如果有更简单的替代方案就好了。 - RKP
如果我选择这种方法,我可以将应用程序设置保存在单独的文件中吗? - RKP
@RKP - 是的,这是免费提供的功能(请参阅ConfigSource属性)。就像您可以为connectionStrings部分拥有单独的文件一样。 - Oded
我的意思是将所有应用程序设置存储在一个文件中,而不是每个部分(例如我的报告)一个文件。这可能吗? - RKP
如果你的部分是这些设置的_集合_,那么是的。 - Oded

3
您不能按照您建议的方式在appsettings中存储xml元素。如果您需要像您提到的那样的层次结构,请尝试以下方法之一。
  1. Store whole xml elements in appsettings an parse the xml

    <appSettings>
      <add key="Report1" value="<Report1 SourceFilePath=""value1"" DestinationFolderPath=""value2"" />" />
      <add key="Report2" value="<Report2 SourceFilePath=""value1"" DestinationFolderPath=""value2"" />" />
    </appSettings>
    
  2. Store the xml in config section (see answers above)

  3. Use the DslConfig project.
    Add it with NuGet and look add the AppSpike for examples.
    In your case you could create a class ReportConfig and use this class as configuration class.
    Example:

    public class Report {
      string SourceFilePath { get; set; }
      string DesinationFolderPath { get; set; }
    }
    
在Variables.var文件中创建一个配置文件条目。
   import ReportClassNamespace from ReportClassAssembly

   Var["Report1"] = Report(SourceFilePath:"value1",DesinationFolderPath:"value2")
   Var["Report2"] = Report(SourceFilePath:"value1",DesinationFolderPath:"value2")
  1. Try the NConfig project

3

您不能按照您的建议进行操作。

您可以按键名对元素进行分组:

<appSettings>
      <add key="Report1:SourceFilePath" value="value1" />
      <add key="Report1:DestinationFolderPath" value="value2" />
      <add key="Report2:SourceFilePath" value="value1" />
      <add key="Report2:DestinationFolderPath" value="value2" />
</appSettings>

最好的方法是定义自己的配置部分。

以下是一些相关链接:


如果我选择这种方法,我可以将应用程序设置保存在单独的文件中吗? - RKP
哪种方法?特殊键名还是配置部分? - Didier Ghys

0
我所知道的最好方法是创建自己的设置类,通过序列化/反序列化来读取/写入应用程序设置。
此外,您还可以使用网站的管理页面将所有设置保存在其中。
也许在您的情况下,最好使用数据库将所有设置保存在那里。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接