ga('set', 'anonymizeIp', 1);
Categories: C#Coding

[C#] ini文件寫入與讀取

Share

Ini文件十分泛用,先前介紹過python的ini文件讀寫,今天介紹的是C#對ini文件的讀寫。

本文介紹如何在C#實現對ini文件讀寫。

pyhon讀寫ini文件請參考此文

創建class

class FileINI:IDisposable
{
    [DllImport("kernal32")]
    private static extern long WritePrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
    
    [DllImport("kernal32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

    private string filepath;
    private bool bDisposed = false;

    public FileINI(string filepath)
    {
        this.filepath = filepath;
    }

    public void WriteIni(string section, string key, string val)
    {
        WritePrivateProfileString(section, key, val, filepath);
    }

    public void ReadIni(string section, string key)
    {
        StringBuilder temp = new StringBuilder(255);
        GetPrivateProfileString(section, key, "", temp, 255, filepath);
        return temp.ToString();
    }

    public void Disposed()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool IsDisposing)
    {
        if(bDisposed)
        {
            return;
        }
        if(IsDisposing)
        {}
        bDisposed = true;
    }
}

INI 範例:

[section1]
val1=VAL01

新建範例:

FileINI ini = new FileINI(Application.StartupPath + "\\test.ini");
string iniread = ini.ReadIni("section1", "val1");
ini.WriteIni("section1", "val2", "VAL02");

上方程式碼將讀取val1之值(VAL01)存入iniread。

並且將test.ini文件內容改為如下:

[section1]
val1=VAL01
val2=VAL02
Jys

Published by
Jys
Tags: C#ini

Recent Posts

[python] Flask Create RESTful API

This article gi... Read More

3 年 前發表

[Javascript] 新增/刪除JSON中key值

在web訊息交換常會需要對JS... Read More

3 年 前發表

[JAVA] SQL Server Connection

本文介紹JAVA連線SQL s... Read More

3 年 前發表