You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#写入文件时diacritic(变音符号)损坏乱码问题如何解决?

问题根源
  • 你使用的Encoding.ASCII本身仅支持0~127范围内的基础英文字符,包含变音符号的非ASCII字符转码时会被强制替换为?,这是你读取时看到乱码的核心原因。
  • 第二种new byte[strContent.Length]的写法完全错误:该操作只会创建一个所有值为0的空字节数组,没有对输入的字符串做任何编码转换,不可能写入正确的文本内容。
修复方案

优先使用UTF-8编码处理文本,UTF-8支持全部Unicode字符,可完美兼容各类语言的变音符号,推荐两种实现方式:

方案1:简化写法(直接调用.NET封装的文本写入方法,无需手动处理流和编码转换)

private static async Task CreateFileFromApiData(string strContent)
{
    var wholePath = PathService.ReturnBinLocation("filename.txt");
    // 方法默认会直接覆盖已存在的文件,无需手动提前删除
    await File.WriteAllTextAsync(wholePath, strContent, Encoding.UTF8);
}

如果需要兼容部分老旧的Windows文本编辑器,可替换为带BOM的UTF-8编码:new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)

方案2:保留原有FileStream逻辑的修复写法

private static async Task CreateFileFromApiData(string strContent)
{
    await using var fs = FileService.CreateFile("filename.txt");
    // 用UTF8编码将字符串转为字节数组
    byte[] content = Encoding.UTF8.GetBytes(strContent);
    await fs.WriteAsync(content.AsMemory(0, content.Length));
}

内容的提问来源于stack exchange,提问作者Nodessa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:54:04