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+.

One Comment

  1. Jim said:

    Great find, thanks for sharing!

    October 18, 2023
    Reply

Leave a Reply

Your email address will not be published.

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