Skip to main content

How to Copy a Folder to the Build Output in a .NET C# Project

· 10 min read
Jagdish Kumawat
Founder @ Dewiride

A .NET app runs from its build output folder, such as bin/Debug/net10.0, and a folder of plain files that you keep beside Program.cs doesn't end up there on its own. One line in the project file copies the whole folder, its subfolders included. Here it is in a small console app, run before and after that line.

Syntax​

Syntax
<ItemGroup>
<None Update="<folder>/**" CopyToOutputDirectory="<when>" />
</ItemGroup>
PartWhat it is
ItemGroupThe element that holds items in a project file. Microsoft's MSBuild reference: Every item that is used in an MSBuild project must be specified as a child of an ItemGroup element.
NoneThe item type for files that are neither compiled nor embedded. Its reference: Represents files that should have no role in the build process.
UpdateChanges items that already exist instead of adding new ones. Its reference: Enables you to modify metadata of an item.
<folder>The folder to copy, relative to the project file.
/**Every file in that folder and in all its subfolders. MSBuild describes ** as the wildcard that matches a partial path.
CopyToOutputDirectoryMetadata, a setting on the item. Its reference: Determines whether to copy the file to the output directory.
<when>Never, Always, PreserveNewest or IfDifferent, the four values the reference lists.

Why Update and not Include: the .NET SDK already turns almost every file in the project folder into an item, without a line in the project file. Its default Include pattern for None items is **/*, every file in every folder, minus a few kinds such as C# files, .resx files and project files, so templates/welcome.txt is a None item before you write anything. Update gives those items a setting. The SDK overview warns against adding the same files again with Include: Duplicating included files causes the build to include the same files twice, which results in a NETSDK1022 build error.

What each value does: Microsoft's guide to content files describes two of them. With Always, the file is copied to the build output folder every time a project is built. With PreserveNewest, only the newest version of the resource is copied to the build output folder. The .NET SDK reference describes the same four values for CopyToPublishDirectory, the matching setting for the publish folder:

ValueWhat the .NET SDK reference says
PreserveNewestOnly copies the item if it has changed in the source location.
IfDifferentOnly copies the item if it has changed either in the source or target location.
AlwaysAlways copies the item.
NeverNever copies the item.

The same page adds: From a performance standpoint, PreserveNewest is preferable because it enables an incremental build. When you don't set CopyToOutputDirectory at all, its value is empty (or Never in a project that sets DefineExplicitDefaults to true), and the file stays where it is, as the first run below shows.

In Visual Studio, the same setting is the file's Copy to Output Directory property: Copy always is Always, and Copy if newer is PreserveNewest.

The Example​

A console app called CopyFolder keeps two text files in a templates folder beside Program.cs: welcome.txt, and reminder.txt in a subfolder called emails. The app looks for the templates folder in the folder it runs from and prints every file in it with its text. It runs once with the project file as dotnet new wrote it, and once with the None item added.

Prerequisites​

  • The .NET 10 SDK.

Step 1: Create a Console App​

Terminal
dotnet new console -n CopyFolder

dotnet new console creates a console app from Microsoft's template, and -n CopyFolder names it and its folder. The template restores the project as soon as it's created:

Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/CopyFolder/CopyFolder.csproj:
Restore succeeded.

Move into the new folder; every command after this one runs there:

Terminal
cd CopyFolder

Step 2: Add the Folder of Files​

In your editor, create a folder called templates in the CopyFolder folder, beside Program.cs, and a folder called emails inside it. Then add the two files:

templates/welcome.txt
Welcome to the team!
templates/emails/reminder.txt
Don't forget the team meeting at 10.

The project folder now looks like this (the obj folder from the restore isn't shown):

CopyFolder
CopyFolder/
├── CopyFolder.csproj
├── Program.cs
└── templates/
├── welcome.txt
└── emails/
└── reminder.txt

Step 3: Read the Folder from Where the App Runs​

Replace everything in Program.cs with this:

Program.cs
// The templates folder next to the app: the folder the app runs from.
string folder = Path.Combine(AppContext.BaseDirectory, "templates");

if (!Directory.Exists(folder))
{
Console.WriteLine($"There is no templates folder in {AppContext.BaseDirectory}");
return;
}

// Every file in the folder and its subfolders, with its text.
foreach (string file in Directory.GetFiles(folder, "*", SearchOption.AllDirectories))
{
Console.WriteLine($"{Path.GetRelativePath(folder, file)}: {File.ReadAllText(file).Trim()}");
}
  • AppContext.BaseDirectory is the app's base directory. Its reference: Gets the file path of the base directory of the application. Path.Combine adds templates to it.
  • Directory.Exists(folder) checks that the folder is there. If it isn't, the app says so, prints the folder it looked in, and stops with return.
  • Directory.GetFiles(folder, "*", SearchOption.AllDirectories) returns every file in the folder, and SearchOption.AllDirectories includes the files in its subfolders.
  • Path.GetRelativePath(folder, file) shortens each file's path to the part after templates, such as emails/reminder.txt, and File.ReadAllText(file).Trim() reads the file's text without the line break at its end.

Step 4: Run It​

Terminal
dotnet run
Output
There is no templates folder in /Users/you/source/CopyFolder/bin/Debug/net10.0/

macOS-style terminal window titled Terminal — CopyFolder showing dotnet run printing There is no templates folder in /Users/you/source/CopyFolder/bin/Debug/net10.0/

The templates folder is in the project, but the app didn't find it. dotnet run builds the app before it runs it; Microsoft's reference: The command depends on the dotnet build command to build the code. The same page says where the build puts its files: Output files are written into the default location, which is bin/<configuration>/<target>. Here that's bin/Debug/net10.0, and the run printed that folder as AppContext.BaseDirectory: the folder that holds the built app. The build wrote the app there, but not the templates folder, because nothing told it to.

Step 5: Copy the Folder to the Build Output​

Open CopyFolder.csproj and add an ItemGroup with the None item below the PropertyGroup:

CopyFolder.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<None Update="templates/**" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>

macOS-style code window titled CopyFolder.csproj — CopyFolder showing the project file of a .NET 10 console app with an ItemGroup that holds one None item, Update set to templates/** and CopyToOutputDirectory set to PreserveNewest

  • Update="templates/**" picks the None items the SDK already made for every file in templates and its subfolders.
  • CopyToOutputDirectory="PreserveNewest" tells the build to copy each of those files to the build output, and to copy only the newest version: the value the SDK reference prefers, because it enables an incremental build.

Step 6: Run It Again​

Terminal
dotnet run
Output
welcome.txt: Welcome to the team!
emails/reminder.txt: Don't forget the team meeting at 10.

macOS-style terminal window titled Terminal — CopyFolder showing dotnet run printing welcome.txt: Welcome to the team! and emails/reminder.txt: Don't forget the team meeting at 10.

This time the build copied the folder, and the app found both files. The subfolder came along as a folder: the second file is emails/reminder.txt in the output too, the same place it has in the project.

The Complete Files​

CopyFolder.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<None Update="templates/**" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>
Program.cs
// The templates folder next to the app: the folder the app runs from.
string folder = Path.Combine(AppContext.BaseDirectory, "templates");

if (!Directory.Exists(folder))
{
Console.WriteLine($"There is no templates folder in {AppContext.BaseDirectory}");
return;
}

// Every file in the folder and its subfolders, with its text.
foreach (string file in Directory.GetFiles(folder, "*", SearchOption.AllDirectories))
{
Console.WriteLine($"{Path.GetRelativePath(folder, file)}: {File.ReadAllText(file).Trim()}");
}

Common Mistakes​

MistakeWhat happensDo this instead
Adding the files with IncludeThe SDK already includes them, and Microsoft warns that duplicates end in a NETSDK1022 build errorUse Update for files inside the project folder
Choosing Always to be safeEvery build copies every file againUse PreserveNewest, or IfDifferent when the copies in the output may change
Editing the copy in bin/Debug/net10.0The build copies the project's file over it once that file changesEdit the file in the project's templates folder

FAQ​

Does this work for a single file?​

Yes. Put the file's name in Update instead of a folder pattern, as in Microsoft's own example: <None Update="appsettings.Development.json" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />.

Can I write CopyToOutputDirectory as an element instead?​

Yes. A setting on an item can be an attribute, as here, or a child element, <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> inside the None element. The MSBuild reference: Any metadata with a name that doesn't conflict with the current list of attributes can be expressed as an attribute.

How do I copy the folder when I publish the app?​

Publishing has its own setting, CopyToPublishDirectory, with the same four values, and one item can carry both, as in Microsoft's example above. Add CopyToPublishDirectory="PreserveNewest" to the same None item.

Where does AppContext.BaseDirectory point when the app runs?​

To the folder that holds the built app. With dotnet run, that's the build output, not the project folder: the first run printed /Users/you/source/CopyFolder/bin/Debug/net10.0/, which is why the templates folder has to be copied there.

Conclusion​

The .NET SDK already treats the files in a templates folder as None items, so <None Update="templates/**" CopyToOutputDirectory="PreserveNewest" /> only has to tell the build to copy them. Before the line, the app found no templates folder in bin/Debug/net10.0. After it, the app read both files, and emails/reminder.txt kept its subfolder.

Additional Resources​