How to Add LICENSE.txt to Your .NET Project Using Azure Pipelines

 Including a license file in your NuGet package is a best practice that improves transparency and compliance for your open-source or internal packages. If you store your LICENSE.txt securely in Azure DevOps, you can automate its inclusion into your .NET project using Azure Pipelines.


In this guide, I’ll walk you through how to:

  1. Download the LICENSE.txt from Azure DevOps secure files
  2. Copy the file into your project directory
  3. Modify the .csproj file dynamically to include the license file during build and packaging


πŸ” Step 1: Download LICENSE.txt from Secure Files

First, upload your LICENSE.txt to the Secure Files library in Azure DevOps. Then, in your YAML pipeline, use the DownloadSecureFile task to fetch it at runtime.

- task: DownloadSecureFile@1
displayName: 'Download LICENSE.txt' inputs: secureFile: 'LICENSE.txt'

This will download the file to a temporary location on the build agent ($(Agent.TempDirectory)).


πŸ“ Step 2: Copy the License File to Your Project

Next, copy the downloaded LICENSE.txt file to your project folder (e.g., src/MyProject/):


- task: CopyFiles@2 displayName: "Copy LICENSE.txt" inputs: sourceFolder: "$(Agent.TempDirectory)" contents: "LICENSE.txt" targetFolder: "$(Build.SourcesDirectory)/src/MyProject/"

This ensures the file will be available in the final build output and can be packed into your NuGet package.


πŸ› ️ Step 3: Modify the .csproj File to Include the License

Finally, you need to update your .csproj file to let the .NET SDK know to include the license file during packaging. We do this by injecting XML tags using sed.

- task: CmdLine@2
displayName: add LICENSE.txt to csproj file inputs: script: | sudo sed -i ''s|</Project>|<PropertyGroup><PackageLicenseFile>LICENSE.txt</PackageLicenseFile></PropertyGroup><ItemGroup><None Include="LICENSE.txt" Pack="true" PackagePath=\"\"/></ItemGroup></Project>|g'' src/MyProject/MyProject.csproj

This script adds the following XML snippet before the closing </Project> tag in your .csproj file:

<PropertyGroup>
<PackageLicenseFile>LICENSE.txt</PackageLicenseFile> </PropertyGroup> <ItemGroup> <None Include="LICENSE.txt" Pack="true" PackagePath=""/> </ItemGroup>

This ensures the license file is:

  • Recognized by the .NET SDK as the package license

  • Included in the resulting NuGet package

  • Placed in the root of the package

πŸ’‘ Tip: If you're using a Windows agent, replace sudo sed -i with a PowerShell-based command.


✅ Final Thoughts

By following these steps, you’ve automated the secure delivery and inclusion of your license file during your CI/CD pipeline. This setup ensures that every NuGet package you build includes the appropriate licensing information without manual intervention.

No comments:

Theme images by merrymoonmary. Powered by Blogger.