Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c# - How to Load Config File Programmatically

Suppose I have a Custom Config File which corresponds to a Custom-defined ConfigurationSection and Config elements. These config classes are stored in a library.

Config File looks like this

<?xml version="1.0" encoding="utf-8" ?>
<Schoool Name="RT">
  <Student></Student>
</Schoool>

How can I programmatically load and use this config file from Code?

I don't want to use raw XML handling, but leverage the config classes already defined.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll have to adapt it for your requirements, but here's the code I use in one of my projects to do just that:

var fileMap = new ConfigurationFileMap("pathtoconfigfile");
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
var sectionGroup = configuration.GetSectionGroup("applicationSettings"); // This is the section group name, change to your needs
var section = (ClientSettingsSection)sectionGroup.Sections.Get("MyTarget.Namespace.Properties.Settings"); // This is the section name, change to your needs
var setting = section.Settings.Get("SettingName"); // This is the setting name, change to your needs
return setting.Value.ValueXml.InnerText;

Note that I'm reading a valid .net config file. I'm using this code to read the config file of an EXE from a DLL. I'm not sure if this works with the example config file you gave in your question, but it should be a good start.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...