When developing application systems, management configuration is essential. For example, the configuration, installation and update configuration of the database server, etc. Due to the rise of Xml, most configuration files are stored in xml documents. For example, Visual's own configuration files, including the configuration files mentioned in the introduction of Remoting, are all in the XML format.
The traditional configuration file ini has tended to be gradually replaced by XML files, but for simple configurations, ini files are still useful. The ini file is actually a text file, which has a fixed format. The name of the section is enclosed with [], and then the line breaks to indicate the value of the key:
[section]
key=value
For example, database server configuration file:
[Server] Name=localhost [DB] Name=NorthWind [User] Name=sa
In C#, reading and writing configuration files are done through API functions, and the code is very simple:
using System; using ; using ; using ; namespace PubOp { public class OperateIniFile { #region API function declaration [DllImport("kernel32")]//Returning 0 means failure, non-0 means success private static extern long WritePrivateProfileString(string section,string key, string val,string filePath); [DllImport("kernel32")]//Return 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 #region Read Ini files public static string ReadIniData(string Section,string Key,string NoText,string iniFilePath) { if((iniFilePath)) { StringBuilder temp = new StringBuilder(1024); GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath); return (); } else { return ; } } #endregion #region Write Ini file public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath) { if((iniFilePath)) { long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath); if(OpStation == 0) { return false; } else { return true; } } else { return false; } } #endregion } }
Briefly explain the parameters of the following methods WriteIniData() and ReadIniData().
No need to mention Section parameter, Key parameter and IniFilePath, the Value parameter indicates the value of the key, and the NoText here corresponds to the def parameter of the API function. Its value is specified by the user. When no specific value is found in the configuration file, the value of NoText is used instead.
NoText can be null or ""
Summarize
The above is the method of reading and writing INI configuration files in C# introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time!