Lỗi font Tiếng Việt khi ghi file INI bằng code C#

  • 5K lượt xem
  • Bài viết cuối 05 Tháng Tám 2019
zeus_link đã gửi 28 Tháng Bảy 2019

Hi bros,

Đệ search trên mạng được cái class này, dùng để đọc và ghi file INI:

    class IniFile   // revision 11
    {
        string Path;
        string EXE = Assembly.GetExecutingAssembly().GetName().Name;

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

        public IniFile(string IniPath = null)
        {
            Path = new FileInfo(IniPath ?? EXE + ".ini").FullName.ToString();
        }

        public string Read(string Key, string Section = null)
        {
            var RetVal = new StringBuilder(255);
            GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
            return RetVal.ToString();
        }

        public void Write(string Key, string Value, string Section = null)
        {
            WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
        }

        public void DeleteKey(string Key, string Section = null)
        {
            Write(Key, null, Section ?? EXE);
        }

        public void DeleteSection(string Section = null)
        {
            Write(null, null, Section ?? EXE);
        }

        public bool KeyExists(string Key, string Section = null)
        {
            return Read(Key, Section).Length > 0;
        }
    }
}

Tuy nhiên khi ghi tiếng Việt thì bị lỗi mất hết chữ có dấu (chuyển thành dấu ?)

Bros nào biết cách xử lý bảo đệ với nha !

 

1 bài viết
gacon đã gửi 05 Tháng Tám 2019

Bro phải ghi 02 bytes vào đầu file INI để hệ thống biết đây là file unicode nhé !

Có thể sửa luôn cái hàm construction ở trên như này nhé:

public clsIniFile(string IniPath = null)
{
FileInfo fi = new FileInfo(IniPath ?? EXE + ".ini");
Path = fi.FullName.ToString();
// Check for existing file
if (!fi.Exists)
{
// Create the file, ghi mồi 02 byte để ấn định encoding file là Unicode utf8
using (FileStream fs = fi.Create())
{
byte[] bom = new byte[2];
bom[0] = 0xff;
bom[1] = 0xfe;
// Add some information to the file.
fs.Write(bom, 0, bom.Length);
fs.Close();
}
}
}

Bạn muốn gửi trả lời ? Hãy đăng nhập trước. Nếu chưa có tài khoản vào diễn đàn, hãy đăng ký
 

Chủ đề cùng danh mục