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

3 Comments

  1. Jim said:

    Great find, thanks for sharing!

    18 October 2023
    Reply
  2. JG said:

    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

    12 January 2024
    Reply
  3. Avrohom Yisroel Silver said:

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

    14 January 2024
    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.