Làm việc với file INI trong c#

Khi lập trình, đôi lúc chúng ta cần lưu những thông số cần thiết để cấu hình cho phần mềm. Cách thông thường là sử dụng các file INI. Ngoài việc lưu các thông số cấu hình thì file ini có thể được sử dụng để lưu các thông tin như là một cơ sở dử liệu. Bên cạnh đó, việc đọc, sửa các thông tin trong file ini thật sự đơn giản bằng các chương trình soạn thảo. Trong c#, việc ghi là đọc dử liệu vào các file ini có thể được thực hiện thông qua một "class" nhỏ sau:

1. Định dạng của file INI như thế nào?

[Section1]
Key1=somevalue
Key2=somevalue
...
[Section2]
Key1=somevalue
Key10=somevalue
...

Nhìn vào định dạng file ini ta cũng hiểu được cách lưu thông tin cuar một file ini.

2. Trong chương trình C#:

Tạo một class:

class INIFile
    {
        private string filePath;
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,
        string key,
        string val,
        string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,
        string key,
        string def,
        StringBuilder retVal,
        int size,
        string filePath);
        public INIFile(string filePath)
        {
            this.filePath = filePath;
        }

        public void Write(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value.ToLower(), this.filePath);
        }

        public string Read(string section, string key)
        {
            StringBuilder SB = new StringBuilder(255);
            int i = GetPrivateProfileString(section, key, "", SB, 255, this.filePath);
            return SB.ToString();
        }

        public string FilePath
        {
            get { return this.filePath; }
            set { this.filePath = value; }
        }
    }

Đọc, ghi trong chương trình:

INIFile inif = new INIFile("D:\\config.ini");
inif.Write("Database", "Ten", "Chapichuse");
inif.Write("Database", "tuoi", "12");
inif.Write("Database", "Gioitinh", "chua biet");
MessageBox.Show(inif.Read("Database", "Ten"));

 

 

 

 

Chapichuse

Đam mê công nghệ

You may also like...

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *