Skip to content

Instantly share code, notes, and snippets.

Created December 27, 2021 12:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ruyut/6314293cd296b15096913813be76d6c0 to your computer and use it in GitHub Desktop.
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);
WriteValueFromIniFile("basic", "k1", "v1", fileName);
WriteValueFromIniFile("basic", "k2", "中文", fileName);
WriteValueFromIniFile("進階", "鍵", "值", fileName);
string value1 = ReadValueFromIniFile("basic", "k1", "null", fileName);
string value2 = ReadValueFromIniFile("basic", "k2", "null", fileName);
string value3 = ReadValueFromIniFile("進階", "鍵", "null", fileName);
[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