如何在具有不同命名空间和 dll 的 C# 脚本中使用外部库

How to use external library in c# script having different namespace and dll

我想在 cs-script 中使用 novacode-docx。我怎样才能正确引用程序集。我尝试了以下但没有解决程序集引用丢失的问题。

//css_reference D:\lib\DocX.dll;
using System;
using System.Diagnostics;
using System.Windows.Forms;

class Script
{
    [STAThread]
    static public void Main(string[] args)
    {
        using (DocX doc = DocX.Create(@"C:\Users\name\Desktop\test.docx"))
        {
             doc.PageLayout.Orientation = Orientation.Landscape;
             var table = doc.AddTable(12, 2); 
             doc.InsertTable(table);
             doc.Save();
        }
    }
}

你读过这个link

To add a reference in Visual C# In Solution Explorer, right-click the project node and click Add Reference. In the Add Reference dialog box, select the tab indicating the type of component you want to reference. Select the components you want to reference, and then click OK.

没有VS:

转到 csproj 文件有一个 <ItemGroup> 可以添加参考:

<ItemGroup>
    <Content Include="libs\...">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
...

在那里你可以添加库。

DocX seems to be available on NuGet,所以我强烈建议从那里获取依赖项,而不是将其放在本地系统的文件中。 (这有助于确保可重复构建,如果您与其他人共享此代码,打包您的应用程序,并且如果发布新版本,它还可以更轻松地升级 DocX。)

如果您使用的是 Visual Studio,您可以在解决方案资源管理器中右键单击该项目并选择 "Manage NuGet Packages..." 打开一个对话框来帮助您安装包,或者您可以打开包管理器控制台并输入 Install-Package DocX.

如果您在没有 Visual Studio 的 .NET Core 上构建,只需将 "DocX": "1.0.0.19" 添加到 project.json 的 dependencies 节点。

安装包后,您可以像导入任何其他名称空间一样using DocX;

出于安全原因,您不能引用这样的显式路径。程序集必须放置在以下位置之一并引用为 //css_reference DocX.dll;

File location The assembly to be loaded must be from one of the following locations (the order indicates the assembly search priority):

  • the same directory where the script is
  • Default Script Library directory Script Library (%CSSCRIPT_DIR%\Lib)
  • Custom Script Library directory(s) (specified in the configuration console SearchDirs)
  • GAC

查看此处了解更多信息:http://www.csscript.net/help/using_.net_assemblies.html

将 Docx.dll 拖放到 cs 脚本所在的同一文件夹中,然后试试这个:

//css_reference DocX.dll;
using System;
using System.Diagnostics;
using System.Windows.Forms;
using Novacode;

class Script
{
    [STAThread]
    static public void Main(string[] args)
    {
        using (DocX doc = DocX.Create(@"C:\Users\name\Desktop\test.docx"))
        {
             doc.PageLayout.Orientation = Orientation.Landscape;
             var table = doc.AddTable(12, 2); 
             doc.InsertTable(table);
             doc.Save();
        }
    }
}

两者都需要才能使用 docx。

//css_reference DocX.dll;
using Novacode;

您也可以参考任何地方,例如

//css_reference D:\lib\DocX.dll;
using Novacode;