C# 写入 INI 文件 中文乱码问题解决方法
问题出现的原因是 INI 文件的编码格式与读取方式不匹配。INI 文件是以 ASCII 编码格式保存的,而在读取时使用了默认的 UTF-8 编码格式,导致中文字符无法正确显示,变成了问号。
解决方法:
- 在写入 INI 文件时,将中文字符转换为 ASCII 编码格式。可以使用 Encoding 类的 GetBytes 方法进行转换,如:'byte[] data = Encoding.ASCII.GetBytes('中文');'
- 在读取 INI 文件时,使用 ASCII 编码格式进行读取。可以使用 Encoding 类的 GetString 方法进行转换,如:'string chinese = Encoding.ASCII.GetString(data);'
示例代码如下:
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
// 写入 INI 文件
WriteIniFile('test.ini', 'Section', 'Key', '中文');
// 读取 INI 文件
string value = ReadIniFile('test.ini', 'Section', 'Key');
Console.WriteLine(value);
}
static void WriteIniFile(string fileName, string section, string key, string value)
{
string path = Path.Combine(Environment.CurrentDirectory, fileName);
// 将中文字符转换为 ASCII 编码格式
byte[] data = Encoding.ASCII.GetBytes(value);
using (StreamWriter writer = new StreamWriter(path, true, Encoding.ASCII))
{
writer.WriteLine($'[{section}]');
writer.WriteLine($'{key}={Encoding.ASCII.GetString(data)}');
}
}
static string ReadIniFile(string fileName, string section, string key)
{
string path = Path.Combine(Environment.CurrentDirectory, fileName);
using (StreamReader reader = new StreamReader(path, Encoding.ASCII))
{
string line;
bool isInSection = false;
while ((line = reader.ReadLine()) != null)
{
line = line.Trim();
if (line.StartsWith('[') && line.EndsWith(']'))
{
isInSection = line.Substring(1, line.Length - 2) == section;
}
else if (isInSection)
{
string[] parts = line.Split('=');
if (parts.Length == 2 && parts[0] == key)
{
// 转换为 UTF-8 编码格式
byte[] data = Encoding.ASCII.GetBytes(parts[1]);
return Encoding.UTF8.GetString(data);
}
}
}
}
return null;
}
}
在上述示例代码中,通过在写入和读取 INI 文件时分别使用 ASCII 编码格式进行转换,可以正常保存和读取中文字符,避免出现问号乱码的问题。
原文地址: https://www.cveoy.top/t/topic/qlzi 著作权归作者所有。请勿转载和采集!