- Code Snippets
- Copying Files Via Project Script On Build
Copying Files Via Project Script On Build

Introduction
Sometimes we need to be able to copy certain files or DLLs to the project output folder location. Visual studio allows you select files to be copied to the output location. But sometiems you may need another way when the project build happens to select a group of files from a folder and have it copied to the output location. This can be done through editing the project file. Below are the steps.
Project Copy Script Example
One way to copy files to output folder is to edit the .csproj file and add a command copy files from a certain directory into the output folder. For example, I have some DLLs at C:\temp\CopyFilesViaProjectScript\Lib that I would like to copy to the output folder when the project is built. It doesn't have to be DLLS, but it could be any types of files that we want to copy.

Files To Copy Location
As an example, my project solution is at the following location C:\temp\CopyFilesViaProjectScript\ So you could place your solution anywhere.

Solution Location
Right click on the project you would like to edit and select Edit Project File. This will allow us the edit the project file. It will open in visual studio.

Edit Project File
The default project file has the following in Visual Studio 2019. You may need to unload the project to edit the project file.
Visual Studio 2019
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>
This is what it looks like in Visual Studio 2022.
Visual Studio 2022
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<RootNamespace>open_project_file</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
I‘m going to add the following ItemGroup to the project lines right after PropertyGroup. Content Include is the path where I am copying the files from. In this example, I have 4 files in the lib folder to copy.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Content Include="..\lib\*.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Visible>false</Visible>
<Link>%(Filename)%(Extension)</Link>
</Content>
</ItemGroup>
</Project>
After building the solution or project, you can see that TestLibrary32Bit.dll, TestLibrary64Bit.dll, and TestLibraryAnyCPU.dll were copied to output folder.
