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

使用C# DocX库操作Word文件遇加载异常,求解决方案及替代库

DocX库加载System.IO.Packaging失败的解决方法及替代库推荐

问题详情

使用DocX 2.2.0版本在C#中创建Word文件时,在Visual Studio和Visual Studio Code中均抛出以下错误:

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.IO.Packaging, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Das System kann die angegebene Datei nicht finden.'

调用栈:

at Xceed.Document.NET.Document.PrepareDocument(Document& document, DocumentTypes documentType) 
at Xceed.Words.NET.DocX.Create(String filename, DocumentTypes documentType) 
at ConsoleApp1.Program.Main(String[] args) in Program.cs:line 13

使用的代码:

using System;
using Xceed.Words.NET;
using Xceed.Document.NET;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"C:\Test\Test.docx";

            var doc = DocX.Create(fileName);

            doc.InsertParagraph("Hello Word");

            doc.Save();
            Console.WriteLine("Hello World!");
        }
    }
}

解决DocX库的当前问题

  • 手动安装System.IO.Packaging NuGet包:DocX 2.2.0依赖该程序集,但可能未自动引入。打开NuGet包管理器,搜索并安装System.IO.Packaging包。
  • 确认项目目标框架兼容性:如果使用.NET Core/.NET 5+版本,确保安装的System.IO.Packaging包版本与目标框架匹配;若为.NET Framework,检查是否引用了WindowsBase程序集(System.IO.Packaging包含在其中)。
  • 清理重建项目:删除项目的bin和obj文件夹,重新生成解决方案,排除依赖缓存问题。

替代库推荐

如果DocX的问题无法快速解决,以下库可满足.docx文件的读写删除需求:

  • NPOI:开源免费,支持多种Office格式(包括.docx),API简洁,无需依赖Office环境。
  • OpenXML SDK:微软官方提供的库,直接操作Office Open XML格式,功能全面,适合需要精细控制Word内容的场景,学习成本略高。
  • Aspose.Words:商业库,功能强大,支持几乎所有Word操作,API友好,适合企业级项目,需付费授权。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:39:23