自动将本机 dll 复制到 Visual Studio 中引用项目的 bin 文件夹

Gae*_*ael 2 c# dll unmanaged visual-studio

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

如果我将构建操作设置为Content,它们将被复制到 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>
Run Code Online (Sandbox Code Playgroud)

bin\nativedll\somelib\x86\somelib.dll如果是 x86,该 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>
Run Code Online (Sandbox Code Playgroud)

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

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

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

daj*_*ric 5

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

<ItemGroup>
   <ContentWithTargetPath Include="mySourcePath\myFile.dll">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    <TargetPath>myFile.dll</TargetPath>
 </ContentWithTargetPath >
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)

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


以下内容也可能有帮助:

在 Visual Studio 项目中本地复制本机依赖项

将 NuGet 包中的本机文件添加到项目输出目录 @kjbartel