我有一些本机DLL,必须在平台条件下复制在bin文件夹中。我希望将它们复制到引用该项目的项目的bin文件夹中。
如果我将构建操作设置为 content ,则将它们复制到bin文件夹中,但是保留了文件夹结构,以便它们不会在bin文件夹中,而是在子文件夹中。因此,在运行程序时,它将无法解析DLL,因为它们在子文件夹中。
例如,如果我在项目文件中有此代码
<Choose>
<When Condition=" '$(Platform)'=='x86' ">
<ItemGroup>
<Content Include="nativedllsomelibx86somelib.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</When>
<When Condition=" '$(Platform)'=='x64' ">
<ItemGroup>
<Content Include="nativedllsomelibx64somelib.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</When>
</Choose>
在x86的情况下,DLL将在文件夹binnativedllsomelibx86somelib.dll
中。
所以我尝试使用Post Build Script
<PostBuildEvent>
IF "$(Platform)" == "x86" (
xcopy /s /y "$(ProjectDir)nativedllsomelibx86" "$(TargetDir)"
)
IF "$(Platform)" == "x64" (
xcopy /s /y "$(ProjectDir)nativedllsomelibx64" "$(TargetDir)"
)
</PostBuildEvent>
但DLL在项目的bin文件夹中复制,而不是在引用该文件的项目的bin文件夹中。
所以我现在的解决方案是使用此项目中的所有项目中添加一个邮政脚本。
在Visual Studio中有更好的方法吗?
尝试对必须复制的每个文件(csproj文件 - 做一个项目组):
<ItemGroup>
<ContentWithTargetPath Include="mySourcePathmyFile.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>myFile.dll</TargetPath>
</ContentWithTargetPath >
</ItemGroup>
引用项目还应包含复制的文件。
以下内容也可能会有所帮助:
在视觉工作室项目中本地复制本地依赖项
将Nuget软件包中的本机文件添加到项目输出目录 @kjbartel
我在得到@dajuric anwser之前使用的解决方案。我更喜欢Dajuric解决方案,因为它不涉及在其他文件夹中查看的代码。
我在csproj中使用了条件内容。
<When Condition=" '$(Platform)'=='x86' ">
<ItemGroup>
<Content Include="nativedllsomelibx86somelib.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</When>
//same for x64
...
然后,在使用本机DLL初始化库之前,我将文件夹添加到DLL查找文件夹列表中,并使用Kernel32 setdLldirectory 。
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
SetDllDirectory(@".nativedllsomelibx"+ (Environment.Is64BitProcess ? "64" : "32"));