• 當前位置:首頁 > IT技術 > Windows編程 > 正文

    C# 讀寫配置文件
    2021-09-17 16:41:04

    利用 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 += "
    ";
                richTextBox1.Text += GetValue("參數", "率特波");
            }
        }
    }
    
    

    界面:

    運行,點擊 button:

    config.ini配置文件內容如下:




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

    本文摘自 :https://www.cnblogs.com/

    開通會員,享受整站包年服務
    国产呦精品一区二区三区网站|久久www免费人咸|精品无码人妻一区二区|久99久热只有精品国产15|中文字幕亚洲无线码