Management configuration is essential for application system development. For example, configure, install, and update the database server. Due to the rise of XML, most configuration files are stored as XML files. For example, Visual Studio. NET's own configuration file mashine. config, ASP. NET's configuration file web. config, including the configuration files I mentioned in remoting, are all in XML format.
The traditional configuration file INI has been gradually replaced by XML files, but for simple configuration, the INI file is still useful. The INI file is actually a text file, which has a fixed format. The section name is enclosed in [], and the key value is displayed in line feed:
[Section]
Key = Value
For example, the database server configuration file:
Dbserver. ini
[Server]
Name = localhost
[DB]
Name = northwind
[User]
Name = sa
In C #, the configuration file is read and written through API functions, and the code is very simple:
Code:
- Using system;
- Using system. text;
- Using system. IO;
- Using system. runtime. interopservices;
- Namespace pubop
- {
- Public class operateinifile
- {
- API function declaration # region API function declaration
- [Dllimport ("Kernel32")] // if the return value is 0, the operation fails. If the return value is not 0, the operation succeeds.
- Private Static extern long writeprivateprofilestring (string section, string key,
- String Val, string filepath );
- [Dllimport ("Kernel32")] // returns the length of the string buffer obtained.
- Private Static extern long getprivateprofilestring (string section, string key,
- String def, stringbuilder retval, int size, string filepath );
-
-
- # Endregion
- Read the INI file # region read the INI File
- Public static string readinidata (string section, string key, string notext, string inifilepath)
- {
- If (file. exists (inifilepath ))
- {
- Stringbuilder temp = new stringbuilder (1024 );
- Getprivateprofilestring (section, key, notext, temp, 1024, inifilepath );
- Return temp. tostring ();
- }
- Else
- {
- Return string. empty;
- }
- }
-
- # Endregion
- Write the INI file # region write the INI File
- Public static bool writeinidata (string section, string key, string value, string inifilepath)
- {
- If (file. exists (inifilepath ))
- {
- Long opstation = writeprivateprofilestring (section, key, value, inifilepath );
- If (opstation = 0)
- {
- Return false;
- }
- Else
- {
- Return true;
- }
- }
- Else
- {
- Return false;
- }
- }
-
- # Endregion
- }
- }
Briefly describe the parameters of writeinidata () and readinidata () in the following methods.
The Section parameter, key parameter, and inifilepath are unnecessary. The value parameter indicates the key value. The notext parameter corresponds to the def parameter of the API function, and the value is specified by the user, when no specific value is found in the configuration file, it is replaced by the value of notext.