Without further ado, let’s get right to the code
1: introduces the namespace
System.Runtime.InteropServices
System.IO
Copy the code
2: Write an iniHelper class
public class IniHelper{[DllImport("kernel32")]// Return 0 for failure, non - 0 for success
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]// Returns the length of the string buffer
private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// <summary>
///Reading an INI File
/// </summary>
/// <param name="Section">The name of the</param>
/// <param name="Key">The keyword</param>
/// <param name="defaultText">The default value</param>
/// <param name="iniFilePath">Ini File address</param>
/// <returns></returns>
public static string GetValue(string Section, string Key, string defaultText, string iniFilePath)
{
if (File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, Key, defaultText, temp, 1024, iniFilePath);
return temp.ToString();
}
else
{
returndefaultText; }}/// <summary>
///Write an INI file
/// </summary>
/// <param name="Section">The name of the</param>
/// <param name="Key">The keyword</param>
/// <param name="defaultText">The default value</param>
/// <param name="iniFilePath">Ini File address</param>
/// <returns></returns>
public static bool SetValue(string Section, string Key, string Value, string iniFilePath)
{
var pat = Path.GetDirectoryName(iniFilePath);
if (Directory.Exists(pat) == false)
{
Directory.CreateDirectory(pat);
}
if (File.Exists(iniFilePath) == false)
{
File.Create(iniFilePath).Close();
}
long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
if (OpStation == 0)
{
return false;
}
else
{
return true; }}}Copy the code
5: You can either manually create an INI file or automatically create an INI file
My INI file is configured like this: [my data] MyID=9527Copy the code
4: Direct call
string MyID = Console.ReadLine();
// Write to the file
string file = System.Environment.CurrentDirectory + @"\config.ini";
if(file! =null)
{
IniHelper.SetValue("My data"."MyID", MyID, file);
}
Console.WriteLine("The ID I entered was {0}",MyID);
// Read the file
if(file ! =null)
{
MyID = IniHelper.GetValue("My data"."MyID"."", file);
Console.WriteLine("The ID I read is {0}"+MyID);
Console.ReadLine();
}
Copy the code