1. 程式人生 > >C# 操作INI檔案的函式 INIClass

C# 操作INI檔案的函式 INIClass

C# CODE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace XXX
{
    public class INIClass
    {


        // 宣告INI檔案的寫操作函式 WritePrivateProfileString()
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);


        // 宣告INI檔案的讀操作函式 GetPrivateProfileString()
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);


        /// <summary> 
        /// 構造方法 
        /// </summary> 
        /// <param name="INIPath">檔案路徑</param> 
        public string inipath;
        public INIClass(string INIPath)
        {
            inipath = INIPath;
        }


        /// <summary> 
        /// 寫入INI檔案 
        /// </summary> 
        /// <param name="Section">配置節(如 [TypeName] )</param> 
        /// <param name="Key">鍵名</param> 
        /// <param name="Value">鍵值</param> 
        public void IniWriteValue(string Section, string Key, string Value)
        {
            // section=配置節,key=鍵名,value=鍵值,filePath=完整路徑和名稱
            WritePrivateProfileString(Section, Key, Value, this.inipath);
        }
        /// <summary> 
        /// 讀出INI檔案 
        /// </summary> 
        /// <param name="Section">專案名稱(如 [TypeName] )</param> 
        /// <param name="Key">鍵</param> 
        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            // section=配置節,key=鍵名,def=無法讀取時預設數值,temp=讀取數值,size=數值的大小,filePath=完整路徑和名稱
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.inipath);
            return temp.ToString();
        }
    }

}

呼叫方法:

INIClass iniDBstr = new INIClass("INI檔案完整路徑(字串形式)");

//讀取

string ConnStr=iniDBstr.IniReadValue("INI檔案裡的Section", "此Section裡的某個Key"); 

//寫入

iniDBstr.IniWriteValue(“INI檔案裡的SectionSection”,"此Section裡的某個Key","要寫入的Value");