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

C#二进制文件写入字符串开头出现错误字符问题求助

问题解决:BinaryWriter写入字符串开头出现错误字符

问题原因

你使用的BinaryWriter.Write(string)方法会自动在字符串内容前添加字符串长度的可变长度编码前缀,这就是你看到的开头两个错误字符的来源——它不是你写入的字符串内容,而是BinaryWriter用于后续读取时识别字符串长度的标记。

解决方案

根据你的需求选择以下两种方法:

方法1:直接写入字符串的字节内容(无长度前缀)

如果目标文件不需要这个长度前缀,将字符串转换为指定编码的字节数组后写入:

public static void WriteFile(string filePath, string content)
{
    try
    {
        // 可根据需求替换为Encoding.ASCII、Encoding.Unicode等编码
        byte[] contentBytes = Encoding.UTF8.GetBytes(content);
        using (BinaryWriter binWriter = new BinaryWriter(File.Open(filePath, FileMode.Create)))
        {
            binWriter.Write(contentBytes);
        }
    }
    catch (Exception err)
    {
        Console.WriteLine(err);
    }
}

方法2:保留长度前缀(用于BinaryReader读取)

如果后续需要用BinaryReader.ReadString()读取该文件,无需修改写入代码,读取时会自动解析前缀并获取完整字符串,此时开头的"错误字符"是正常的格式标记,无需处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:15:35