c# - 自动将 native dll复制到Visual Studio中引用项目的bin文件夹中

标签 c# visual-studio dll unmanaged

我有一些 native dll,必须根据平台条件将其复制到 bin 文件夹中。我希望将它们复制到引用该项目的项目的 bin 文件夹中。

如果我将构建操作设置为内容,它们将被复制到 bin 文件夹,但保留文件夹结构,因此它们不会位于 bin 文件夹中,而是位于子文件夹中。因此,当运行程序时,它将无法解析该dll,因为它们位于子文件夹中。

例如,如果我的项目文件中有此代码

<Choose>
    <When Condition=" '$(Platform)'=='x86' ">
      <ItemGroup>
        <Content Include="nativedll\somelib\x86\somelib.dll">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </Content>
      </ItemGroup>
    </When>
    <When Condition=" '$(Platform)'=='x64' ">
      <ItemGroup>
        <Content Include="nativedll\somelib\x64\somelib.dll">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </Content>
      </ItemGroup>
    </When>
  </Choose>

对于 x86,该 dll 将位于文件夹 bin\nativedll\somelib\x86\somelib.dll 中。

所以我尝试使用构建后脚本

<PostBuildEvent>

            IF "$(Platform)" == "x86" (
            xcopy /s /y "$(ProjectDir)\nativedll\somelib\x86" "$(TargetDir)"
            )
            IF "$(Platform)" == "x64" (
            xcopy /s /y "$(ProjectDir)\nativedll\somelib\x64" "$(TargetDir)"
            )
</PostBuildEvent>

但是 dll 被复制到项目的 bin 文件夹中,而不是复制到引用它的项目的 bin 文件夹中。

所以我现在的解决方案是在使用此脚本的所有项目中添加一个后期构建脚本。

在 Visual Studio 中是否有更好的方法来执行此操作?

最佳答案

尝试对每个需要复制的文件使用此方法(csproj 文件 - 创建项目组):

<ItemGroup>
   <ContentWithTargetPath Include="mySourcePath\myFile.dll">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    <TargetPath>myFile.dll</TargetPath>
 </ContentWithTargetPath >
</ItemGroup>

引用项目还应包含复制的文件。


以下内容也可能有帮助:

Copy native dependencies locally in a Visual Studio project

Add native files from NuGet package to project output directory @kjbartel

关于c# - 自动将 native dll复制到Visual Studio中引用项目的bin文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361127/

相关文章:

c# - 如果没有项目,如何使用 DataTrigger 隐藏数据网格容器

c# - 我应该重用 FileStream/BinaryWriter 对象吗?

c++ - 在头文件中编写的类的成员函数的定义,在 C++ 中单独的 .cpp 文件中

c++ - Visual Studio 2008,运行时库使用建议

java - 您可以通过编程方式在 Java 中注册 ActiveX dll 吗?

c++ - 如何将结构从 C++ 应用程序传递到 C++ Win32 DLL?

c# - ASP.NET MVC2 访问控制 : How to do authorization dynamically?

c# - PushSharp Apple 通知从版本 4.0.10.0 到 Testflight 的问题

visual-studio - 将 Visual Studio 资源文件转换为文本文件?

c++ - 如何处理 "This application has failed to start because myproject.dll was not found."错误