C#里面读写ini文件

date
Nov 14, 2021
slug
10009
status
Published
tags
C#
summary
type
Post

Preface

Firstly, read this MSDN blog post on the limitations of INI files. If it suits your needs, read on.
This is a concise implementation I wrote, utilising the original Windows P/Invoke, so it is supported by all versions of Windows with .NET installed, (i.e. Windows 98 - Windows 10). I hereby release it into the public domain - you're free to use it commercially without attribution.

The tiny class

Add a new class called IniFile.cs to your project:
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

// Change this to match your program's normal namespace
namespace MyProg
{
    class IniFile   // revision 11
    {
        string Path;
        string EXE = Assembly.GetExecutingAssembly().GetName().Name;

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

        public IniFile(string IniPath = null)
        {
            Path = new FileInfo(IniPath ?? EXE + ".ini").FullName;
        }

        public string Read(string Key, string Section = null)
        {
            var RetVal = new StringBuilder(255);
            GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
            return RetVal.ToString();
        }

        public void Write(string Key, string Value, string Section = null)
        {
            WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
        }

        public void DeleteKey(string Key, string Section = null)
        {
            Write(Key, null, Section ?? EXE);
        }

        public void DeleteSection(string Section = null)
        {
            Write(null, null, Section ?? EXE);
        }

        public bool KeyExists(string Key, string Section = null)
        {
            return Read(Key, Section).Length > 0;
        }
    }
}

How to use it

Open the INI file in one of the 3 following ways:
// Creates or loads an INI file in the same directory as your executable
// named EXE.ini (where EXE is the name of your executable)
var MyIni = new IniFile();

// Or specify a specific name in the current dir
var MyIni = new IniFile("Settings.ini");

// Or specify a specific name in a specific dir
var MyIni = new IniFile(@"C:\Settings.ini");
You can write some values like so:
MyIni.Write("DefaultVolume", "100");
MyIni.Write("HomePage", "http://www.google.com");
To create a file like this:
[MyProg]
DefaultVolume=100
HomePage=http://www.google.com
To read the values out of the INI file:
var DefaultVolume = MyIni.Read("DefaultVolume");
var HomePage = MyIni.Read("HomePage");
Optionally, you can set [Section]'s:
MyIni.Write("DefaultVolume", "100", "Audio");
MyIni.Write("HomePage", "http://www.google.com", "Web");
To create a file like this:
[Audio]
DefaultVolume=100
[Web]
HomePage=http://www.google.com
You can also check for the existence of a key like so:
if(!MyIni.KeyExists("DefaultVolume", "Audio"))
{
    MyIni.Write("DefaultVolume", "100", "Audio");
}
You can delete a key like so:
MyIni.DeleteKey("DefaultVolume", "Audio");
You can also delete a whole section (including all keys) like so:
MyIni.DeleteSection("Web");

函数形式读写
private void IniFileSave()
{
var myIni = new IniFile("p2g-nawozou-config.ini");
myIni.Write("Input_File", InputTextBox.Text);
myIni.Write("Output_File", OutputTextBox.Text);
myIni.Write("FGSP", FGSPTextBox.Text);
myIni.Write("LGSP", LGSPTextBox.Text);
myIni.Write("MinChan", MinChanTextBox.Text);
myIni.Write("MaxChan", MaxChanTextBox.Text);
myIni.Write("Seperator", SeperatorTextBox.Text);
myIni.Write("ToDesktop", OutputToDesktopCheckBox.Checked ? "True" : "False");
}
private void IniFileLoad()
{
var myIni = new IniFile("p2g-nawozou-config.ini");
InputTextBox.Text = myIni.Read("Input_File");
OutputTextBox.Text = myIni.Read("Output_File");
FGSPTextBox.Text = myIni.Read("FGSP");
LGSPTextBox.Text = myIni.Read("LGSP");
MinChanTextBox.Text = myIni.Read("MinChan");
MaxChanTextBox.Text = myIni.Read("MaxChan");
SeperatorTextBox.Text = myIni.Read("Seperator");
if (myIni.KeyExists("ToDesktop")) OutputToDesktopCheckBox.Checked = Convert.ToBoolean(myIni.Read("ToDesktop"));
}
使用:
public Form1()
{
InitializeComponent();
IniFileLoad();
if (File.Exists(InputTextBox.Text))
        {
            LogTextBox.Text = File.ReadAllText(InputTextBox.Text);
        }
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            IniFileSave();
        }

© Wen Bo 2021 - 2022