1. 程式人生 > 其它 >C# 讀寫配置檔案

C# 讀寫配置檔案

利用 Windows API 讀寫配置檔案。

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CS讀寫配置檔案
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        [DllImport("kernel32")]//讀配置檔案方法的6個引數:所在的分割槽(section)、 鍵值、     初始預設值、   StringBuilder、  引數長度上限 、配置檔案路徑
        public static extern long GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);
        [DllImport("kernel32")]//配置檔案方法的4個引數:  所在的分割槽(section)、  鍵值、     引數值、       配置檔案路徑
        private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

        /*讀配置檔案*/
        public static string GetValue(string section, string key)
        {
            // ▼ 獲取當前程式啟動目錄
            string strPath = Application.StartupPath + @"/config.ini";
            if (File.Exists(strPath)) {
                StringBuilder sb = new StringBuilder(255);
                GetPrivateProfileString(section, key, "配置檔案不存在,讀取未成功!", sb, 255, strPath);

                return sb.ToString();
            }
            else {
                return string.Empty;
            }
        }
        /*寫配置檔案*/
        public static void SetValue(string section, string key, string value)
        {
            // ▼ 獲取當前程式啟動目錄
            string strPath = Application.StartupPath + @"/config.ini";
            WritePrivateProfileString(section, key, value, strPath);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetValue("引數", "波特率", "9600"); // 都是字串型別
            SetValue("引數", "率特波", "110"); // 都是字串型別
        }

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Text += GetValue("引數", "波特率");
            richTextBox1.Text += "\n";
            richTextBox1.Text += GetValue("引數", "率特波");
        }
    }
}

介面:

執行,點選 button:

config.ini配置檔案內容如下:




參考:
1.link-01 // Windows API 讀寫配置檔案
2.link-02 // 在C#中讀寫INI配置檔案