当前位置:   article > 正文

c# 解决ini中文乱码_ini配置文件保存的是乱码

ini配置文件保存的是乱码

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

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

方法一 : 有可能出问题

  1. public class IniConfig
  2. {
  3. private string inipath = AppDomain.CurrentDomain.BaseDirectory + "Config1.ini";
  4. public bool CanRead()
  5. {
  6. if (File.Exists(inipath))
  7. {
  8. return true;
  9. }
  10. return false;
  11. }
  12. //声明API函数
  13. [DllImport("kernel32")]
  14. private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
  15. [DllImport("kernel32")]
  16. private static extern long WritePrivateProfileString(string section, string key, byte[] retVal, string filePath);
  17. [DllImport("kernel32")]
  18. private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
  19. [DllImport("kernel32")]
  20. private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
  21. /// <summary>
  22. /// 写入INI文件
  23. /// </summary>
  24. public void IniWriteValue(string Section, string Key, string Value)
  25. {
  26. WritePrivateProfileString(Section, Key, Value, inipath);
  27. }
  28. public void IniWriteValue(string Section, string Key, string Value, Encoding encoding)
  29. {
  30. byte[] retVal = encoding.GetBytes(Value);
  31. WritePrivateProfileString(Section, Key, retVal, inipath);
  32. }
  33. /// <summary>
  34. ///读INI文件: 含有中文时,请使用此方法 Encoding.Default
  35. /// </summary>
  36. public string IniReadValue(string Section, string Key, Encoding encoding)
  37. {
  38. try
  39. {
  40. byte[] Buffer = new byte[200];
  41. int bufLen = GetPrivateProfileString(Section, Key, "", Buffer, Buffer.GetUpperBound(0), inipath);
  42. string s = encoding.GetString(Buffer);
  43. s = s.Substring(0, bufLen);
  44. return s.Trim();
  45. }
  46. catch (Exception)
  47. {
  48. return "";
  49. }
  50. }
  51. public string IniReadValue(string Section, string Key)
  52. {
  53. try
  54. {
  55. StringBuilder temp = new StringBuilder(500);
  56. int i = GetPrivateProfileString(Section, Key, "", temp, 500, inipath);
  57. return temp.ToString();
  58. }
  59. catch (Exception)
  60. {
  61. return "";
  62. }
  63. }
  64. }

调用:

 IniConfig ic = new IniConfig();

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

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

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

//没有中文直接调用

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

备注:  有可能出现  本机调试好用,目标机修改ini后就不正常了

原因:依旧是ini默认编码不一样,大概就是uft-8  与utf-8 bom的事情了 

**************尚不知道怎么蹦出来的bom*******************

解决办法:在新电脑上重新生成ini文件,指定Encoding.UTF8就可以了

一劳永逸的办法就是采用下面的类库

直接指定编码格式

方法二:

  1. public class IniFile
  2. {
  3. private string filePath = AppDomain.CurrentDomain.BaseDirectory + "Config.ini";
  4. private Dictionary<string, Dictionary<string, string>> sections = new Dictionary<string, Dictionary<string, string>>();
  5. public IniFile()
  6. {
  7. Load();
  8. }
  9. private void Load()
  10. {
  11. sections.Clear();
  12. if (!File.Exists(filePath))
  13. {
  14. return;
  15. }
  16. //使用 utf-8 格式读取
  17. using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8))
  18. {
  19. string line;
  20. string sectionName = null;
  21. while ((line = reader.ReadLine()) != null)
  22. {
  23. line = line.Trim();
  24. if (line.StartsWith(";") || line.Length == 0)
  25. {
  26. // 注释或空行,忽略
  27. continue;
  28. }
  29. if (line.StartsWith("[") && line.EndsWith("]"))
  30. {
  31. // 新节开始
  32. sectionName = line.Substring(1, line.Length - 2).Trim();
  33. sections[sectionName] = new Dictionary<string, string>();
  34. }
  35. else
  36. {
  37. // 键值对
  38. int index = line.IndexOf('=');
  39. if (index > 0)
  40. {
  41. string key = line.Substring(0, index).Trim();
  42. string value = line.Substring(index + 1).Trim();
  43. if (!string.IsNullOrEmpty(sectionName))
  44. {
  45. sections[sectionName][key] = value;
  46. }
  47. }
  48. }
  49. }
  50. }
  51. }
  52. private void Save()
  53. {
  54. //默认 utf-8 格式
  55. using (StreamWriter writer = new StreamWriter(filePath, false))
  56. {
  57. foreach (var section in sections)
  58. {
  59. writer.WriteLine($"[{section.Key}]");
  60. foreach (var setting in section.Value)
  61. {
  62. writer.WriteLine($"{setting.Key}={setting.Value}");
  63. }
  64. writer.WriteLine(); // 空行分隔不同的节
  65. }
  66. }
  67. }
  68. public string Get(string section, string key)
  69. {
  70. if (sections.ContainsKey(section) && sections[section].ContainsKey(key))
  71. {
  72. return sections[section][key];
  73. }
  74. return null;
  75. }
  76. public void Set(string section, string key, string value)
  77. {
  78. if (!sections.ContainsKey(section))
  79. {
  80. sections[section] = new Dictionary<string, string>();
  81. }
  82. sections[section][key] = value;
  83. Save();
  84. }
  85. }

调用: 

IniFile iniFile = new IniFile();

//写入

iniFile.Set("fan", "aaaa", "你好啊1");

//读取

iniFile.Get("fan", "aaaa")

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/300269
推荐阅读
相关标签
  

闽ICP备14008679号