Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A slightly more complicated, but far more flexible, alternative is to create a class that represents a configuration section. In your <code>app.config</code> / <code>web.config</code> file, you can have this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;!-- This section must be the first section within the &lt;configuration&gt; node --&gt; &lt;configSections&gt; &lt;section name="DirectoryInfo" type="MyProjectNamespace.DirectoryInfoConfigSection, MyProjectAssemblyName" /&gt; &lt;/configSections&gt; &lt;DirectoryInfo&gt; &lt;Directory MyBaseDir="C:\MyBase" Dir1="Dir1" Dir2="Dir2" /&gt; &lt;/DirectoryInfo&gt; &lt;/configuration&gt; </code></pre> <p>Then, in your .NET code (I'll use C# in my example), you can create two classes like this:</p> <pre><code>using System; using System.Configuration; namespace MyProjectNamespace { public class DirectoryInfoConfigSection : ConfigurationSection { [ConfigurationProperty("Directory")] public DirectoryConfigElement Directory { get { return (DirectoryConfigElement)base["Directory"]; } } public class DirectoryConfigElement : ConfigurationElement { [ConfigurationProperty("MyBaseDir")] public String BaseDirectory { get { return (String)base["MyBaseDir"]; } } [ConfigurationProperty("Dir1")] public String Directory1 { get { return (String)base["Dir1"]; } } [ConfigurationProperty("Dir2")] public String Directory2 { get { return (String)base["Dir2"]; } } // You can make custom properties to combine your directory names. public String Directory1Resolved { get { return System.IO.Path.Combine(BaseDirectory, Directory1); } } } } </code></pre> <p>Finally, in your program code, you can access your <code>app.config</code> variables, using your new classes, in this manner:</p> <pre><code>DirectoryInfoConfigSection config = (DirectoryInfoConfigSection)ConfigurationManager.GetSection("DirectoryInfo"); String dir1Path = config.Directory.Directory1Resolved; // This value will equal "C:\MyBase\Dir1" </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload