c# 解决ini中文乱码

乱码仅仅是因为编码规则导致

c# 解决ini中文乱码_第1张图片

解码时对应文件的码制即可

    public class IniConfig
    {
        private string inipath = AppDomain.CurrentDomain.BaseDirectory + "Config.ini";
        public bool CanRead()
        {
            if (File.Exists(inipath))
            {
                return true;
            }
            return false;
        }
        //声明API函数

        [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, byte[] retVal, int size, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        ///  
        /// 写入INI文件 
        ///  
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.inipath);
        }
        ///  
        /// 读出INI文件 
        ///  
        public string IniReadValue(string Section, string Key, Encoding encoding)
        {
            try
            {
                byte[] Buffer = new byte[500];
                int bufLen = GetPrivateProfileString(Section, Key, "", Buffer, Buffer.GetUpperBound(0), this.inipath);
                string s = encoding.GetString(Buffer);
                s = s.Substring(0, bufLen);
                return s.Trim();
            }
            catch (Exception)
            {
                return "";
            }
        }
        public string IniReadValue(string Section, string Key)
        {
            try
            {
                StringBuilder temp = new StringBuilder(500);
                int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);
                return temp.ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }
    }

调用:

 IniConfig ic = new IniConfig();

 if (!ic.CanRead())
 {ic.IniWriteValue("DataBase", "Connect", "你好啊");}

//有中文时指定编码格式

ic.IniReadValue("DataBase", "Connect", Encoding.UTF8);

//没有中文直接调用

ic.IniReadValue("DataBase", "Connect");

你可能感兴趣的:(c#,c#,服务器)