NEWS

[C#] Hướng dẫn ghi thông tin cài đặt setting form vào file INI

[C#] Hướng dẫn ghi thông tin cài đặt setting form vào file INI
Đăng bởi: Thảo Meo - Lượt xem: 13288 08:22:05, 21/12/2017C#   In bài viết

Bài viết hôm nay, mình sẽ hướng dẫn các bạn ghi các thuộc tính cài đặt của winform vào file setting INI file C#.

1. Tổng quan một file ini

Dưới đây là cấu trúc của một file setting như sau:

[Section]
Key=Value

Ví dụ mình muốn lưu cái "Tự động đăng nhập" cho phần mềm của mình thì File ini sẽ có dạng sau :

[TuDongDangNhap]
KichHoat=1
TaiKhoan=buiducduy111

2. Thực hiện trong C#

2.1 . Đừng quên " using System.Runtime.InteropServices;" để có thể sử dụng các hàm API
2.2. Sử dụng DLL :  kernel32

[DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filepath);

OK vậy là bạn có thể Đọc/Ghi dữ liệu từ file setting theo cách trên

Nếu chưa làm được hãy xem code dưới đây (Bạn chỉ cần sử dụng INI.READ và INI.WRITE thôi)

public class INI
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filepath);

public static string READ(string szFile, string szSection, string szKey)
        {
            StringBuilder tmp = new StringBuilder(255);
            long i = GetPrivateProfileString(szSection, szKey, "", tmp, 255, szFile);
            return tmp.ToString();
        }
        public static void WRITE(string szFile, string szSection, string szKey, string szData)
        {
            WritePrivateProfileString(szSection, szKey, szData, szFile);
        }
    }

3. Thực hành
Ví dụ : (Sử dụng class INI được xây dựng bên trên)

INI.WRITE("Data.ini","TuDongDangNhap","TaiKhoan", "buiducduy");
INI.WRITE("Data.ini","TuDongDangNhap","KichHoat", "1");

Kết quả trong Data.ini :
[TuDongDangNhap]
TaiKhoan=buiducduy111
KichHoat=1

string s = INI.READ("Data.ini","TuDongDangNhap","TaiKhoan");
MessageBox.Show(s);

Kết quả "buiducduy";

OK. Nếu chưa hiểu bạn cứ comment ở dưới nhé!

 

Theo thuvienwinform

Tags:

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn ghi thông tin cài đặt setting form vào file INI
Đăng bởi: Thảo Meo - Lượt xem: 13288 08:22:05, 21/12/2017C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.