How can I make a .NET class library read its own configuration file?

前端 未结 7 838
予麋鹿
予麋鹿 2020-12-13 15:10

I have a .NET class library that provides a set of helper functions that are used by several Web Services. This class library must store a single setting, specifically, a co

7条回答
  •  情话喂你
    2020-12-13 15:48

    A year out of date I know, but I used this method to read each of the settings:

    Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
    ConfigurationSectionGroup csg = config.GetSectionGroup("applicationSettings");
    ClientSettingsSection c = (ClientSettingsSection)csg.Sections["Add your section name here, e.g. Your.Namespace.Properties.Settings"];
    foreach (SettingElement e in c.Settings)
    {
        Debug.WriteLine("SETTING NAME: " + e.Name);
        SettingValueElement v = e.Value;
        Debug.WriteLine("SETTING VALUE: " + v.ValueXml.InnerText);
    }
    

    This works on a settings file created in a Class Library Project. The settings file should be named "YourLibrary.dll.config" and then deployed in the library's location. The settings file should have similar content to this:

    
    
      
        
          
    http://localhost:3861/YourWebService.asmx False

    I haven't needed to read connection strings from the config file, but that should be possible by changing the name of the section group that you get after opening the exe configuration.

    The reason why I needed to do this is that I have a User Control which wraps a ActiveX/COM library which is then hosted in IE in an "object" tag. I have got the use of "param" tags working, so I could have used that mechanism to have passed the settings into the User Control, but this method seemed a logical choice at the time. Plus I wasn't going to let this particular problem beat me!

    HTH pridmorej :)

提交回复
热议问题