Go C # operation INI file

Source: Internet
Author: User
Tags read ini file

In a lot of programs, We will see a file with an. ini suffix, this file can be very convenient to set up and read some of the program configuration information, such as when we do a program background login, need to automatically log in or remote configuration database connection, and save password settings and so on (in the WinForm program), if in the ASP. NET Program There is another workaround, this C # action INI file article only writes and reads in the WinForm program.

For the sake of convenience, the C # operation INI file is now explained in a simple small instance:

The approximate layout of the form is as follows

When the Write button is clicked, the value entered in the text box is written to the INI file, and the result is

When you click the Read button, the value of the node information in the INI file is populated into the text box in the form

The above is the entire process of working with the INI file in C #, now to describe how the background code is implemented:

Above the project namespace, add the following references:

Using system.runtime.interopservices;//reference namespaces

Then the background of the program to declare some of the variables of the system functions, the code is as follows

declaring Variables#region"Declaring variables"/// <summary>        ///Write INI file/// </summary>        /// <param name= "section" >node name [e.g. [TypeName]]</param>        /// <param name= "key" >Key</param>        /// <param name= "val" >value</param>        /// <param name= "filepath" >file path</param>        /// <returns></returns>[DllImport ("kernel32")]        Private Static extern LongWritePrivateProfileString (stringSectionstringKeystringValstringfilepath); /// <summary>        ///Read INI file/// </summary>        /// <param name= "section" >Node name</param>        /// <param name= "key" >Key</param>        /// <param name= "def" >value</param>        /// <param name= "RetVal" >Stringbulider Object</param>        /// <param name= "Size" >byte size</param>        /// <param name= "FilePath" >file path</param>        /// <returns></returns>[DllImport ("kernel32")]        Private Static extern intGetPrivateProfileString (stringSectionstringKeystringDef,stringbuilder retval,intSizestringFilePath); Private stringstrFilePath = Application.startuppath +"\\FileConfig.ini";//Get INI file path        Private stringStrsec ="";//INI file name                 #endregion

First explain that my INI configuration file is placed in the program's Debug folder, and then click the Write button, before writing to write the value of the validation, the code is as follows:

Write Event//Write button Events        Private voidBtnwrite_click (Objectsender, EventArgs e) {            Try            {                     //set the name of the node to write to the INI file according to the INI filename//the node name here can be configured exactly as neededStrsec =path.getfilenamewithoutextension (strFilePath); WritePrivateProfileString (Strsec,"Name", TxtName.Text.Trim (), strFilePath); WritePrivateProfileString (Strsec,"Sex", TxtSex.Text.Trim (), strFilePath); WritePrivateProfileString (Strsec," Age", TxtAge.Text.Trim (), strFilePath); WritePrivateProfileString (Strsec,"Address", TxtAddress.Text.Trim (), strFilePath); MessageBox.Show ("Write Success"); }Catch(Exception ex) {MessageBox.Show (ex).                        Message.tostring ()); }        }

Running this instance will write the value to the INI file, and the result will be written as if the second effect is displayed. We then click the Read button event to populate the form's text box with the information in the INI file, with the following code:

Read Events//Read button Events        Private voidBtnread_click (Objectsender, EventArgs e) {            if(File.exists (strFilePath))//read the INI file first to see if it exists{strsec=path.getfilenamewithoutextension (strFilePath); txtName.Text= Contentvalue (Strsec,"Name"); Txtsex.text= Contentvalue (Strsec,"Sex"); Txtage.text= Contentvalue (Strsec," Age"); Txtaddress.text= Contentvalue (Strsec,"Address"); }            Else{MessageBox.Show ("INI file does not exist"); }        }

At the time of reading, a custom read function is used, and the system function is called in the method.

}      /// <summary>      ///customizing content methods in the Read INI file/// </summary>      /// <param name= "section" >Key</param>      /// <param name= "key" >value</param>      /// <returns></returns>        Private stringContentvalue (stringSection,stringkey) {StringBuilder temp=NewStringBuilder (1024x768); GetPrivateProfileString (section, key,"", temp,1024x768, strFilePath); returntemp.        ToString (); }

The above is a simple operation of the INI file in the C # language, using only two of the system functions (write functions and read functions) and other functions such as the deletion of INI file functions, etc., the removal of the INI file function is actually the key corresponding to the value set to NULL is OK.

Automatic login and connection settings are used in the INI file, the end of the article.

Reference Link: Mr. Chess's Blog: C # operation INI file

Go C # operation INI file

Related Article

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.