Select Page
This entry has been published on 2019-02-22 and may be out of date.

Last Updated on 2019-02-22.

[:en]

Goal

We want to include an unmanaged DLL file to our VS project which produces a NuGET .nupkg output. We are using .NET Framework v4.6.1 in this case (should be equal with similar versions).

The unmanaged file should be included within the generated .nupkg automatically. Referencing the NuGET package in other projects, the unmanaged file should also be copied to that project’s output automatically.

Steps

We don’t need a .nuspec file. Instead, we edit the .csproj file of the project which produces the .nupkg.

Before the final “project” end tag, we add or append/edit the ItemGroup tag like:

<ItemGroup>
<None Include=”unmanaged.dll” Pack=”true” PackagePath=”build\”>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include=”unmanaged.targets” Pack=”true” PackagePath=”build\”>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

With this configuration, the 2 mentioned files will be added to the .nupkg file, under a separated “build” subfolder.

The file unmanaged.dll should exist in your project’s root directory. In addition, we create a new file “unmanaged.targets” there, and insert:

<Project xmlns=”http://schemas.microsoft.com/developer/msbuild/2003″>
<ItemGroup>
<NativeLibs Include=”$(MSBuildThisFileDirectory)**\*.dll” />
<None Include=”@(NativeLibs)”>
<Link>%(RecursiveDir)%(FileName)%(Extension)</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

The .targets file ensures that your unmanaged file is copied to the Debug/Release output of the project where you are actually using your NuGET package.

Build your NuGET project, the .nupkg file should be created and contains your unmanaged file.

 

Update: Publishing unmanaged DLL via ClickOnce

If you have finished the steps above, the unmanaged file is copied to Debug output, but will not yet be published if you deploy your final app via ClickOnce method. You might get FileNotFoundExceptions.

To achieve this, you have to add a link to your unmanaged file from your ClickOnce project.

So one way would be to install your NuGet package, then go to your project’s solution and add a reference to an existing element, which is your unmanaged file within your project’s “packages\MyNugetModule” folder. I recommend adding it as a link instead of the file (see the dropdown in the dialog!). In the file’s properties, choose “Copy if newer”.

Finally, the file should be included in your ClickOnce deployment.

 

References

https://stackoverflow.com/questions/19478775/add-native-files-from-nuget-package-to-project-output-directory

https://stackoverflow.com/questions/51217832/including-unmanaged-dll-in-nuget-package-using-csproj

 

 [:]