Created
December 27, 2021 12:26
-
-
Save ruyut/6314293cd296b15096913813be76d6c0 to your computer and use it in GitHub Desktop.
C# ini settings read and write example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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