看範例學C#-25 ini檔讀寫範例

  • 30423
  • 0
  • C#
  • 2011-10-07

看範例學C#-25 ini檔讀寫範例

通常一個ini檔除了檔名還分為三部分

[section]
[name]=[value]
我們有時候會需要把檔案存在本機,但純文字檔每次都要一行一行讀
如果我們要取某一行的值,就不是那麼方便,所以通常我會把資訊存成ini檔
這範例在Form1_Load的部分做 讀檔取值的動作,按button就是存值進去

要注意全域變數都是放在public Form1()上面

public partial class Form1 : Form
{
    public string filename = "language.ini";//要注意全域變數都是放在public Form1()上面
    public Form1()
    {
        InitializeComponent();
    }

在這邊因為我都是讀寫同一個檔案,所以把檔名設成全域變數

 

以下為本例完整程式碼


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
namespace ex25
{
    public partial class Form1 : Form
    {
        public string filename = "language.ini";
        SetupIniIP ini = new SetupIniIP();
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ini.IniWriteValue("lng", "lang1", textBox1.Text, filename);
            ini.IniWriteValue("lng", "lang2", textBox2.Text, filename);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists(Application.StartupPath + "\\" + filename))
                {
                    textBox1.Text = ini.IniReadValue("lng", "lang1", filename);
                    textBox2.Text = ini.IniReadValue("lng", "lang2", filename);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
    public class SetupIniIP
    {
        public string path;
        [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 void IniWriteValue(string Section, string Key, string Value, string inipath)
        {
            WritePrivateProfileString(Section, Key, Value, Application.StartupPath + "\\" + inipath);
        }
        public string IniReadValue(string Section, string Key, string inipath)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, Application.StartupPath + "\\" + inipath);
            return temp.ToString();
        }
    }
}

ex24.rar


如有錯誤 歡迎指正