繁体   English   中英

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

[英]Automaticaly copy native dll to the bin folder of referencing project in 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>

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

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

<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>

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


以下内容也可能会有所帮助:

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

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

我给出了@dajuric anwser之前使用的解决方案。 我更喜欢dajuric解决方案,因为它不涉及在其他文件夹中查找代码。

我在csproj中使用了条件内容。

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

然后,在使用本机dll初始化库之前,我使用kernel32 SetDllDirectory将文件夹添加到dll查找文件夹列表中。

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetDllDirectory(string lpPathName);

 SetDllDirectory(@".\nativedll\somelib\x"+ (Environment.Is64BitProcess ? "64" : "32"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM