Unwanted changes in .csproj file on build

2019-08-28 05:54发布

问题:

I'm trying to auto-detect web.configs as part of a transform pre-build event in one of my web application project files, this code goes up one folder level from my project file and gets all web.configs in every directory and sub directory:

<ItemGroup>
    <WebConfigsRelativePath Include ="..\**\Web.config"/>
</ItemGroup>

This works great but everytime I build and exit Visual Studio, I get a prompt asking me if I want to save changes made to my solution file. If I select yes, and open the project file, the above code is changed to the locations of each web.config

<ItemGroup>
    <WebConfigsRelativePath Include="..\Web\Decade\Web.config" />
    <WebConfigsRelativePath Include="..\Web\Matrix\RiskAnalysis\Web.config" />
    <WebConfigsRelativePath Include="..\Web\Service\Web.config" />
    <WebConfigsRelativePath Include="..\Web\Web.config" />
</ItemGroup>

This would be fine but the whole reason I'm auto-detecting web.configs pre-build is so I can add and remove web.configs as I please without having to hardcode their locations, and everytime I exit VS, the locations will be hardcoded in the project file....

Does anyone know why this ItemGroup changes every time I exit Visual Studio?

回答1:

If I take an existing web project but use the <Content /> rather than the custom <WebConfigsRelativePath /> in your sample, then I see the expected behavior.

Try using this:

<Content Include="..\**\Web.config">
  <SubType>Designer</SubType>
</Content>

Edit:

If you have special handling for the WebConfigsRelativePath item group, post that in an update to your question.



回答2:

While I can't explain why VS decides to output a list of files retrieved by the wildcard each time my solution is built, I can show you how I got around this issue:

<PropertyGroup>
    <WebConfigsSearchString>..\**\Web.config</WebConfigsSearchString>
</PropertyGroup>

<ItemGroup>
    <WebConfigsRelativePath Include ="$(WebConfigsSearchString)"/>
</ItemGroup>

By defining the search string in a property (which always stays static) and referencing the property in the item group's list of files to include, the item group code is never modified but the web.config search is carried out each time a build is run