close

 

 [C#]ini讀寫教學

為什麼要用ini(initialization)?

可以方便的作讀寫的動作,比單純存在程式內更有效率,因為假若存在程式裡,程式移動位置時內部資料就會跑掉。此外,當然也可以選用.txt、.conf、.cfg作為存檔方式。

 

接下來先來介紹

private static extern long WritePrivateProfileString(string section,
string key, string val, string filePath);

● string section INI文件中的一個字段名
● string key下的一個鍵名,也就是一個變數
● string val 寫入的字串
● string filePath 路徑名稱

private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal,
int size, string filePath);

● string section INI文件中的一個字段名
● string key下的一個鍵名,也就是一個變數
● string val 寫入的字串
● string def 如果沒有其前兩個參數值,則將此值賦給變量
● StringBuilder retVal接收INI文件中的值的String對象,即接收緩衝區
● int size 大小

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
namespace ini讀寫
{
    public partial class Form1 : Form
    {
        [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 string filename = "ini_Hello.ini"; //your file name
    

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            WritePrivateProfileString("section1", "var1", textBox1.Text, ".\\" + filename);
            WritePrivateProfileString("section2", "var1", textBox2.Text, ".\\" + filename);
            WritePrivateProfileString("section1", "var2", textBox3.Text, ".\\" + filename);
         
        }

   

        private void button2_Click_1(object sender, EventArgs e)
        {
            int size = 3000;//temp file source size
            StringBuilder temp = new StringBuilder(size); //temp file source
            try
            {
                GetPrivateProfileString("section1", "var1", "", temp, size, ".\\" + filename);
                textBox1.Text = Convert.ToString(temp);
                GetPrivateProfileString("section2", "var1", "", temp, size, ".\\" + filename);
                textBox2.Text = Convert.ToString(temp);
                GetPrivateProfileString("section1", "var2", "", temp, size, ".\\" + filename);
                textBox3.Text = Convert.ToString(temp);
            }
            catch
            {

            }
       }  

    }
}

 未命名C  

範例下載(解壓縮密碼:um):

輕輕點我

arrow
arrow
    全站熱搜

    UM程式研究日誌 發表在 痞客邦 留言(0) 人氣()