Skip to content

Instantly share code, notes, and snippets.

@ruyut
Created December 27, 2021 12:26
Embed
What would you like to do?
C# ini settings read and write example
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace RuyutConsoleApp
{
class Program
{
static void Main(string[] args)
{
string fileName = "RuyutConsoleApp.ini";
fileName = Path.GetFullPath(fileName);
Console.WriteLine("WriteIniFile");
WriteValueFromIniFile("basic", "k1", "v1", fileName);
WriteValueFromIniFile("basic", "k2", "中文", fileName);
WriteValueFromIniFile("進階", "鍵", "值", fileName);
Console.WriteLine("ReadIniFile");
string value1 = ReadValueFromIniFile("basic", "k1", "null", fileName);
string value2 = ReadValueFromIniFile("basic", "k2", "null", fileName);
string value3 = ReadValueFromIniFile("進階", "鍵", "null", fileName);
Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(value3);
}
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
public static void WriteValueFromIniFile(string section, string key, string value, string filePath)
{
WritePrivateProfileString(section, key, value, filePath);
}
public static string ReadValueFromIniFile(string section, string key, string def, string filePath)
{
StringBuilder temp = new StringBuilder(4096);
int i = GetPrivateProfileString(section, key, def, temp, 4096, filePath);
return temp.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment