开发者

.NET Configuration File - Should I Use OpenMappedExeConfiguration

To begin I have a .NET 2.0 console application. To meet a customer requirement, I need to use a configuration file which is in a different directory than my application in a read/write manner. This is in addition to the exe configuration which my app already has (ie appname.exe.config).

So to do this, I added a property Configuration which returns a Configuration object obtained from a call to OpenMappedExeConfiguration().

I'm trying to step back an re-evaluate this implementation. What I wrote seems really hackish. Is this even the right approach? I read through a lot of material on .net configuration files, but I'm still not sure exactly what I should do.

    class LocalEnvironment {

    ... stuff 

    static Configuration _cfg;

    internal static Configuration Configuration {
开发者_运维问答        get {

            if (_cfg == null) {
             var fm = new ExeConfigurationFileMap
                         {
                             ExeConfigFilename = Path.Combine(ApplicationInstallDirectory,
                                                              "config.xml")
                         };

                _cfg = ConfigurationManager.OpenMappedExeConfiguration(fm, ConfigurationUserLevel.None);
            }
            return _cfg;
        }
    }
}


Why not just refer to the other file from the standard .config file?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings file="..\RelativePathTo\MoreSettings.config">
  ...
  </appSettings>
</configuration>

MoreSettings.config

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
    <add key="Something" value=""/>
</appSettings>


This is what I do, and it's a heck of a lot simpler and more flexible. In this linked post there is example code - so it's even already written for you. :-)

(.Net) suggestions on making a config file for a program?


I will do the same thing. No better solution I could found.


There are valid reasons to do what you're doing. For example svcutil.exe (.net framework SDK tool) offers a /svcutilConfig switch which the user can use to cause a particular config file to be loaded as svcutil.exe's config file. This is needed so that the user can extend and customize the code generation process; these extensions are specified in config only.

The code you have is basically the same as what svcutil.exe does, and appears to be the best way to do this.

That said, it's worth stepping back and considering whether you really need to let the user replace the entire config file. As other posters have commented, perhaps it would be adequate just to give access to appSettings, which you can do more simply.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜