How to add a post-publish event to Visual Studio

How to add a post-publish event to Visual Studio

For various reasons not worth explaining here, I don't rely on the various versions of appSettings.json, but rather leave a correct one sitting on the server, and then just ignore the one created when publishing.

That works fine for manual publishing (ie to file, then manually copied to the server using FTP), as long as I remember not to copy the published one to the server! However, for automatic publishing, this won't work.

I just discovered that you can add a command to be executed before or after publishing. I can't find this documented anywhere on the MSDN docs, but have verified that it does work.

If you open your .pubxml file, and add the following...

  <Target Name="CustomActionsAfterPublish" AfterTargets="AfterPublish">
    <Message Text="About to delete appSettings.json" Importance="high" />
    <Exec Command='del "C:\Path\To\Published\Files\appSettings.json"' />
  </Target>

...then after publishing, appSettings.json will be deleted. I had to fiddle a bit with the single and double quotes to get this to work, but the way shown here is fine.

You can also run a command before publishing, using BeforeTargets="BeforePublish", but I'm not sure how useful that is.

The <Message> line is documented, but far less useful.

Note that <Exec> only works in VS2019+.

Comments

Jim 18th October 2023

Great find, thanks for sharing!

JG 12th January 2024

Thanks for sharing.



Is there a way to use current solution path ?

My goal is to make a copy of the solution after publish

Thanks

Avrohom Yisroel Silver 14th January 2024

@JG Great question! I did a quick search and found that there are macros for these events (see https://learn.microsoft.com/en-us/visualstudio/ide/reference/pre-build-event-post-build-event-command-line-dialog-box?view=vs-2022#macros). One of these is $(ProjectDir), which is described as "The directory of the project (defined with drive and path); includes the trailing backslash '\'." Guess that would do it.

I'll give it a go and update the post.

Allen 13th May 2025

It doesn't work for me

Parth Savjadiya 1st July 2025

Nice blog! Simple yet impactful.

Timothy 7th November 2025

"BeforePublish" // very useful for initially deleting the publish folder contents.

Avrohom Yisroel Silver (Owner) 19th May 2026

Thanks for pointing that out.

Leave a comment