Search code examples
c#visual-studiobuildlocationapp-config

C# - Save app.config file to subfolder when building


I am trying to clean up the base directory of my WinForms app's build folder (built in .NET 6 using Visual Studio 2022). I have already moved the log4net config file to a Config subfolder and changed the call to the AddLog4Net() extension method to reflect this new location.

I am now trying to get the main App.config file (which holds tons of other configuration for this app) to save to that same subfolder during builds. It is currently being saved to the root directory (and renamed to SomeWinFormsApp.dll.config in the process) and I'm trying to alter this behavior so that file is saved in the Config subfolder instead and get the app to read it from there.

Even if I move the app.config file to the Config subfolder in the project, Visual Studio still creates the renamed copy in the root folder.

Is there a way to automate this during the build process and not have to move it myself every time?


Solution

  • I fixed this by combining a post-build event with a one liner on the AppDomain :

    move "$(TargetDir)SomeWinFormsApp.dll.config" "$(TargetDir)Config"
    
    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "Config//SomeWinFormsApp.dll.config");
    

    Do note that in order for this same manipulation to be automated during the publish process, you can add this to the csproj file :

    <Target Name="PostPublish" AfterTargets="Publish">
        <Exec Command="move &quot;$(PublishDir)SomeWinFormsApp.dll.config&quot; &quot;$(PublishDir)Config&quot;" />
    </Target>
    

    Seems to work like a charm!