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

使用OpenXml将Dotx转Docx时出现“Word发现不可读内容”错误

问题分析与解决

你的代码导致Word弹出“发现不可读内容”错误的核心原因是使用MemoryStream.GetBuffer()获取字节数组——这个方法会返回MemoryStream的整个底层缓冲区,其中包含未被实际写入的空字节,这些冗余数据会让Word判定文件存在损坏。

修正后的代码

public static void Generate()
{
    // 简化MemoryStream创建逻辑,无需自定义读取方法
    using MemoryStream stream = new MemoryStream(File.ReadAllBytes(@"c:\Templates\TemplateTest.dotx"));

    using (WordprocessingDocument wpd = WordprocessingDocument.Open(stream, true))
    {
        wpd.ChangeDocumentType(WordprocessingDocumentType.Document);
    }

    // 使用ToArray()获取实际有效字节,避免冗余空字节
    File.WriteAllBytes(@"c:\Templates\TemplateTestOutput.docx", stream.ToArray());
}

关键修改点

  • 移除冗余的ReadAllBytesToMemoryStream方法:直接通过new MemoryStream(File.ReadAllBytes(path))即可创建包含文件内容的MemoryStream,无需手动写入和指针定位。
  • 替换stream.GetBuffer()为stream.ToArray():ToArray()仅返回MemoryStream中实际写入的有效字节,彻底消除冗余数据引发的解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:05:39