How to add folders in .net core webapi to Publish directory

When you add a folder in your project, your .csproj file gets modified as shown below:

<ItemGroup>
	<Folder Include="AppData\" />
	<Folder Include="OfflineFiles\2019\" />
</ItemGroup>

To add a folder to the Publish directory with some pre-existing contents, add the below ItemGroup in your .csproj file:

<ItemGroup>
	<Content Include="OfflineFiles\**">
		<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
	</Content>
</ItemGroup>

If you have a folder without any pre-existing content, add the below Target action in the .csproj file:

<Target Name="CreateAppDataFolder" AfterTargets="AfterPublish">
	<MakeDir Directories="$(PublishUrl)AppData" Condition="!Exists('$(PublishUrl)AppData')" />
</Target>

If you check the WebPublishMethod (.pubxml file under Properties folder) which in this is case is FileSystem, the publishUrl contains the directory where the files are published:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <PublishProvider>FileSystem</PublishProvider>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <ProjectGuid>xxxx</ProjectGuid>
    <publishUrl>C:\Path</publishUrl>
    <DeleteExistingFiles>False</DeleteExistingFiles>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <SelfContained>false</SelfContained>
  </PropertyGroup>
</Project>

I’m using .net core 3.1 for the above method. This method might vary in other versions of .net core.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.