[CodeProject C #] ReadWrite Config Files

xiaoxiao2021-03-06  41

http://www.codeproject.com/csharp/readwritexmlini.asp

Contents

Introduction Interface Classes USAGE DEMO

Introduction

I was developing a small Windows app using C # and I decided that it would be nice to save the window's position and size when the app exited so it would be the same the next time the app was run. Having come from the MFC world, I searched for something equivalent to GetProfile and WriteProfile methods of the CWinApp class, but found nothing. I knew there was a Registry class in the Microsoft.Win32 namespace, but there was nothing available for writing to INI files. I would need to use the Win32 APIs for those. If I wanted to use an XML file, there was a whole slew of classes available in the System.Xml namespace. I also looked into using App.config files which some people had mentioned in the forums, but those supposedly were Not Meant to Be Written To ...

All these Similar Mechanisms, Each with their owned interface ... Which one to use? I Just Needed WAS A Simple Way to Persist My WINDOW'S POSITION AND SIZE SOMEWHERE to Be Later Retrieved.

I set my small Windows app project on the side and decided that it was time to write a new class library; one that would unify all these mechanisms into a common and simple interface:. The IProfile interface This article presents the IProfile interface and the four Classes That Implement IT: XML, Registry, INI, AND Config. Thase Four Classes Allow Reading and Writing Values ​​To Their Respective Mediums, Via A Common And Simple Interface. Enjoy!

Interface

SO What Does this Common Interface Look Like? Here's a Simplified Version of It - See iProfile.cs or Ams.profile.chm for the completion definition:

Interface IPROFILE

{

Void SetValue (String Section, String Entry, Object Value); Object getValue (String Section, String Entry);

String getValue (String Section, String Entry, String DefaultValue);

INT getValue (String Section, String Entry, Int defaultValue);

Double getValue (String Section, String Entry, Double DefaultValue);

Bool getValue (String Section, String Entry, Bool DefaultValue);

String [] geTENTRYNAMES (STRING Section);

GetsectionNames ();

Void Removentry (String Section, String Entry);

Void Removesection (String Section);

Bool Readonly

{

Get;

SET;

}

Event ProfilechanGingHandler Changing;

Event profilechangedhandler change;

}

As you can see, it's a simple interface bearing a slight resemblance to the GetProfile and WriteProfile methods of the CWinApp class It's all based on a simple paradigm:.. A piece of data is associated with an entry inside of a section The section may contain multiple entries and there may be multiple sections available. That's it! A section could be something like "Main Window", holding entries such as "X", "Y", "Width", "Height", each one having their corresponding numeric Values. If You'Ve Worked with INI Files in The Past, this concept will be very familia to you.

Aside from the standard Get and Set methods used to read and write the values, the interface also allows you to retrieve the names of the available entries and sections, and to remove them if desired. It even has a ReadOnly property to prevent any changes to . the profile And to top it off, it contains two events that allow you to be notified when something in the profile (section, entry, or value) is about to change or has already changed (I may have gone a little overboard.: -)) Classes

When it came time to implement the interface I went with the most popular mediums available. XML was number one on the list. It's popularity is just impossible to ignore. The Registry was my second choice. Although people may be turning away from it, it's still a very efficient way to read and write data to a centralized location. lastly, I went with INI files. I realize they're practially extinct these days but some people still use them due to their simplicity. Once I had completed my classes, I decided to add one more implementation to the list: one to handle config files From the forums and articles here at CP, I noticed several developers needing a way to write to them So I said, "Why not?" It's somewhat similar.. To The Xml One So It Didn't take long to write.

.

SO How do these classes Store THEIR PROFILE DATA? Here's A Brief Synopsis of How each class works:

Xml

As you probably know, XML is all about storing data inside a text file in pretty much any markup-based format. So which format would I choose to organize the data using the section / entry paradigm? After considering a couple of possibilities, I decided that the format below would be preferable, since it allows section and entry names to contain spaces. It also looks cleaner and more consistent than if I had used the section and entry names themselves to name the elements.Some Value

Another Value

True

Notice the root element is called "profile". This is the default root name, which you may change via the class's RootName property. When you check out the class, you'll also notice that the default name of the XML file is based on The name of the application - Program.exe.xml. this, of course, is also ready.

Registry

For the registry I decided to default to the old familiar path, HKEY_CURRENT_USER / Software / Company / Product, with individual sections appearing as a subkeys of that. Again, this path is customizable when creating the object, or later via the RootKey and Name properties .

The Above Data Would Appear Similar To this, When Viewed On The Registry Editor (regedit.exe):

- My Computer

...

- HKEY_CURRENT_USER

...

- Software

...

- AMS

- ProfileDemo

- a section name data

An entry spot value

Another Entry Another Value

- Another Section Name Data

This is cool true

Ini

INI Files Are Pretty Much Self Explanatory, Format-Wise. Here's The Above Data in INI Format:

[A section]

An entry = Some Value

Another entry = another value

[Another section]

This is cool = TRUE

Like the Xml File, The Default File Name Will Be Based on The Name of the Application - Program.exe.ini. If you don't like it it, it's easy enough to change via the constructor or name proteth.config

Config Files Are The Most and Complex of the Bunch, Format and Code Wise. Let Me Begin by Illustrating How The Above Data Would Look:

As you can see, there's a lot more going on here than with the other formats. The profile element contains an element for each section and the values ​​are kept as attributes of add elements. Notice that for each section, the configSections element needs to specify how to read the values ​​contained by it This is all standard fare, required for the framework to properly load the values ​​and allow you to retrieve them using the System.Configuration.ConfigurationSettings class, like this.:

NameValueCollection Section = (NameValueCollection)

ConfigurationSettings.getConfig ("profile / a_section");

String value = section ["an entry";

Notice there's also an "appSettings" element, which was not part of the other samples. I just threw in there just to show that it may also be accessed via the Config class. If you're familiar with the System.Configuration namespace, You'll Know That Appsettings Is The Default Section Used for Storing Application-Specific Settings That May Be Read Using The ConfigurationSettings.AppSettings Property:

String value = configurationSettings.appsettings ["app entry"];

Well, The Config Class Also Allows you to read (and of course, write) to That Section, As Follows:

CONFIG CONFIG = New Config ();

Config.groupname = null; // don't use the "profile" group

...

String value = config.getValue ("AppSettings", "App Entry", NULL; Config.SetValue ("AppSettings", "Update Date", DateTime.toDay);

One thing to keep in mind is that .NET caches the config data as it reads it, so any subsequent updates to it on the file will not be seen by the System.Configuration classes. The Config class, however, has no such problem since The Data Is Read from The File Every Time.

Like the Xml and Ini classes, the default file name will be based on the name of the application -. Program.exe.config This is the name expected by the .NET framework classes, but you can still change it if you want.

USAGE

So now that you've seen the classes, how do you go about using them in your code? Well, I packaged them inside their own DLL, called AMS.Profile.dll. This makes them easy to use in your various projects, without Having to Recompile The THEM EVERYWHERE. Simply Add The DLL Your Project's References, Which is Done As Follows Inside Visual Studio .NET:

Open your own project inside Visual Studio .NET. Inside the Solution Explorer toolbox, right click on the References folder and select "Add Reference". Click on the Browse button and select the AMS.Profile.dll file. Click OK. You may now Use the ams.profile namespace inside your project.

Which Class Should I use?

OK, so how do you actually use these classes inside the code? That's the easy part, actually. The hard part may be deciding which one of the four to use. Whereas before you may have based your decision on the amount and complexity of the code involved, now that's no longer an issue. now you just worry about which storage medium is best for the job. and that part is basically up to your program's requirements and / or personal preferences.Here are some of my observations to help you decide :

When you bring up the Demo program you'll see a Test button. It's used to test most of the functionality of the selected Profile to verify it's working as expected. Well, I added some simple timing code to the method to measure how long the test takes for the selected profile The end result:.. the Registry profile is by far the fastest of the four (especially after the first time) The Ini profile came in at a distant second, followed by Xml, and then Config Ironic,. is not it? The newer technologies are also the slowest. Granted, the difference is one or two hundred milliseconds, which is probably not noticeable, but still, it may be something to keep in mind. According to many people, config files are Not Meant to Be Written At Run-Time. The lack of .Net Methods for doing so proned. a better alternative is the xml class which is meant to work with a separate file. INI Files May Be Old and Gray, But for Storage Of Small Data They're Still Hard to Beat, As Far As Their Format Goes.

STILL TRYING to DECIDE? Here's The Bottom Line.

Use the Config class only if you absolutely need to write to the app.config file, or for your own file. Use the Ini class if your program works with legacy data stored in INI files. Use the Registry class if you do not want to deal with extra files, or if you require high performance. Use the Xml class if you need to make it easy to transfer the whole app to another location, or to add an extra element of coolness to your app. ;-) Even if You don't pick the property Class from the start, it's ketore to switch to another one later. OOP ROCKS!

How do I use the class?

Now that you have selected the profile class for the job, how do you use them inside your code Well, most of the time you'll just declare the class as a field of another class and then call the GetValue and SetValue methods?:

XML profile = new xml ();

...

Int width = profile.getValue ("Main Window", "Width", 800);

INT Height = Profile.GetValue ("Main Window", "Height", 600);

...

Profile.SetValue ("Main Window", "Width", this.size.width;

Profile.SetValue ("Main Window", "Height", this.size.height;

As you saw from the IProfile interface, there are several other methods, properties, and events available. Those you'll find fully documented inside the code, as well in the AMS.Profile.chm help file. I recommend you double click on the Help file to get the completion detail.com The dll. of course, if you have questions or concerns, you may address theme.................

Demo

I wrote the demo program to illustrate the functionality of the four Profile classes, and at the same time, to test the classes. I added a Test button that calls a method of the Profile base class to verify that the most important methods and properties work correctly and consistently across all profiles. You may want to check out that code for examples of how to use these classes.Keep in mind that this is just a demo program, not a utility. Each Profile object works with their default Names. for example For the XML Object, The Name of the File Will Be demo.xml and will be located in the Same Folder As Demo.exe. There's no provision for Changing these names, since, again, it's just a demo.

To use the demo, select a Profile from the top combo box. This will cause the sections in the profile to be placed into the Section combo. Choose a section from there and you'll see all of its entries get added to the Entry combo box. Choose an entry from there and you'll see its value placed into the value textbox. If you want to add a new Section or entry, simply type it into the proper combo box. Press the Save button to write the value to the Profile Via SetValue. This SHOULD All Be Pretty StraightForward, I hope. if not, please let me know.

History

Version 1.0 - OCT 23, 2003

INITIAL RELEASE. Version 1.1 - Mar 15, 2004

转载请注明原文地址:https://www.9cbs.com/read-118317.html

New Post(0)