I assume you were creating your code using STM32CubeMX or STM32CubeIDE, right?
Both are based on the same principles and by default should create the project with Keep User Code when re-generating enabled. Please double check your settings by opening the IOC file and navigating to Project Manager > Code Generator --> Keep User Code ...
If you check the generated code, you will find many comment lines like
/* USER CODE BEGIN <block_name> */
...
/* USER CODE END <block_name> */
while <block_name> can be Header, Includes, PTD, PD, etc.
If the above setting is enabled, changing and / or re-creating the project will not change your user code if it is between these comments.
Does it help?
Good luck!
/Peter