". Net deep breathing" modifies the app configuration file at run time

Source: Internet
Author: User
Tags allkeys

In the previous blog post, the old week's self-authored configuration class, although well encapsulated, allows only the user-level configuration to be modified, so the files are saved to the User Configuration directory. However, in many cases, we do not consider user isolation, but can directly modify the application directory with the app. config file.

So, can you edit the app. Config file in a code file? Of course it's possible. In fact, the configuration file is essentially an XML document, so you can modify it by editing the normal XML file. However, the. NET class Library also provides a dedicated API with read-write profiles, using a dedicated API to make the generated configuration comparison specification.

A. NET configuration file consists of n configuration sections, each of which targets different features, such as the. NET Framework version that startup can configure for a program. For ease of administration, our application settings are usually placed on the AppSettings section and the XML node is AppSettings. Each configuration is relatively simple, consisting of key and value.

To manipulate the configuration file, you remember to reference the System.Configuration.dll assembly , because the System assembly contains only a few general types, and the type that is used to read and write the configuration file is wrapped to System.Configuration Assembly. These APIs are applicable to both app. Config and the Web. config file.

OK, the above paragraphs of nonsense as long as you understand, then we can start to work. Rest assured, very simple, the old week to you to share things, has always been simple and practical value.

First, the old week introduces the approximate type of use process.

Read --reading the contents of the AppSettings section in the App. Config file is simple, using the ConfigurationManager class, which exposes two static properties, do not underestimate them, and with these two properties, it is much easier to read the configuration. ConnectionStrings: The database connection, you must be familiar with it, the node is dedicated to the connection string; AppSettings: This special access to the AppSettings node under the content, the presentation is very concise, is key-value to, And all of them are string types.

Write -write changes can be slightly more complicated, but not difficult.

A, ConfigurationManager class has a static method openexeconfiguration, you can specify the exe file path, it automatically find a matching app. config file, and then open, return a Configuration The instance of the type.

b, the configuration class can be modified, after the modification, you can drop the Save method, or call the SaveAs method to save the configuration to other files.

Next, in an example of an old week, after this example is run, you can set the date on the computer to explode on the window, and when the window is closed, it will be written to the appsettings node in the configuration file. As shown in.

It's just a joke, the computer doesn't really explode.

In general, we will read the values in the configuration file when the window is loaded so that the user's last set content is displayed on the interface, or the user will mistakenly assume that the configuration is missing.

            var q = ConfigurationManager.AppSettings.AllKeys.AsQueryable ();             var  from inch where Select C;             if 0 )            {                string datestr = configurationmanager.appsettings[bomb_date];                 = DateTime.Parse (datestr);            }

Before I read the application configuration, I queried with a LINQ statement to see if the settings I want to access exist, and if there are no settings to set, read a feather. The key of the set section is represented by a string, and bomb_date is a constant that I define.

Const string " bombdate ";

The setting values in the configuration file are saved as strings, and the controls on our window require instances of the DateTime type, so read them and remember to Parse.

Next, let's look at how to modify and save the App. Config file.

Convert the date selected by the user to a string in the date selection control first.

            DateTime seldate = Picker. SelectedDate?? datetime.today;             string forstr = seldate. ToShortDateString ();

Then, you have to get the EXE path of the current program.

string ExePath = Environment.getcommandlineargs () [0];

The first element in the string array returned by the GetCommandLineArgs method is the path to this program's EXE.

Call the Configurationmanager.openexeconfiguration static method to open the App. Config file.

            Configuration config = configurationmanager.openexeconfiguration (exepath);

Then, the key part is writing the settings.

            if(config. AppSettings.Settings.AllKeys.Count (s = = = Bomb_date) >0)            {                //if the setup item already exists//is directly modified                varKV =CONFIG.                Appsettings.settings[bomb_date]; Kv. Value=Forstr; }            Else            {                //if the setting item does not exist//The new item is addedCONFIG.            APPSETTINGS.SETTINGS.ADD (Bomb_date, FORSTR); }

Here is a very serious content, we must, special attention. You'll have to decide if the key for the setup item already exists, because if you call the Add method directly, if the key of the set item already exists, it will not replace the entire value, but instead append the content after the original value.

For example, in this case, if I write to 2017/10/1, the first time I save, because the setting item does not exist, so no problem. However, once I change the value to 2017/11/5 and then save it, the value of the set item becomes

1/One/5 

That is, the newly saved content is not replaced, but appended, and each value is separated by a comma.

As a result, it is troublesome to read, and such a string cannot be converted to a DateTime instance.

So, here to analyze first, if the setup item already exists, then through the indexer to get the content of this setting, it is encapsulated with a keyvalueconfigurationelement class, where the Value property can be modified (key cannot be changed, so read only), at this time, As long as we assign a new value directly to the Value property, the original value is overwritten when it is saved, not appended later. And if the set item does not exist, it is too good to do, directly add a method to do it.

Finally, the changes are finished, do not forget to save, do not save the words will not be written to the app. config file.

            if (config. AppSettings.SectionInformation.IsLocked)            {                //  If the configuration section is locked, discard save                return ;            }            Config. Save (configurationsavemode.modified);

Before saving the detection IsLocked property, is to see if this configuration section is locked, if the lock, you can not save.

In the configuration file, you can use this method to keep a node locked.

    <lockitem= "true">        ...

</ appSettings >

When locked, the node will not allow others to edit it. Of course, you can manually open the configuration file is able to change, I said in the code with the API can not be changed.

When invoking the Save method of a Configuration instance, you can pass a ConfigurationSaveMode enumeration value to the method, where I use Modified, which means that only the modified nodes are written, which saves time and effort.

The appsettings node for the Saved App. Config file is as follows.

    < appSettings >        <  key= "Bombdate"  value= "2017/7/28"/>    </  appSettings>

=================================================

For the above example source code download, please click here?

How, after learning to use it. Almost forgot to say that if you put the exe file in a directory that requires administrator privileges such as program files, you must run the application as an administrator to save the configuration file.

". Net deep breathing" modifies the app configuration file at run time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.