![](/img/trans.png)
[英]Visual Studio building solution does not copy dll to bin folder, but building project does
[英]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>
引用項目還應包含復制的文件。
以下內容也可能會有所幫助:
我給出了@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.