问题
I am trying to include stylecop.json in my C# project on Visual Studio 2017. I have figured out how to do this by modifying the .csproj in any text editor:
<AdditionalFiles Include="stylecop.json">
<Link>stylecop.json</Link>
</AdditionalFiles>
I am wondering if there is a way to do this without making any text edits. I understand I can always add it like any other files but that would make a copy of the file within project folder and not link it externally.
回答1:
You can add a Directory.Build.targets file somewhere in your solution directory (will apply to all projects at or below that directory) with the following contents:
<Project>
<ItemGroup>
<AdditionalFiles Update="@(AdditionalFiles)">
<Link Condition="'%(Link)' == ''">%(Identity)</Link>
</AdditionalFiles>
</ItemGroup>
</Project>
Note that using %(Identity) here isn't optimal for items outside the "project cone" - e.g. when you have <AdditionalFiles Include="..\..\foo.bar" />. For this you can use a mechanism similar to what SDK-based projects will do in VS 2017 15.3 / .net core 2.0 tooling:
<Project>
<ItemGroup>
<AdditionalFiles Update="@(AdditionalFiles)">
<LinkBase Condition="'%(LinkBase)' != ''">$([MSBuild]::EnsureTrailingSlash(%(LinkBase)))</LinkBase>
<Link Condition="'%(Link)' == '' And !$([MSBuild]::ValueOrDefault('%(FullPath)', '').StartsWith($([MSBuild]::EnsureTrailingSlash($(MSBuildProjectDirectory)))))">%(LinkBase)%(RecursiveDir)%(Filename)%(Extension)</Link>
</AdditionalFiles>
</ItemGroup>
</Project>
This will even preserve directory hierarchies of items matched with e.g. ..\shared\**\*.json and the target folder could be set using the LinkBase metadata:
<AdditionalFiles Include="..\shared\**\*">
<LinkBase>SharedFiles</LinkBase>
</AdditionalFiles>
Note that you may need to close and re-open the solution after making changes to Directory.Build.targets. In the upcoming VS 2017 15.3 update, changes will be monitored by VS automatically. In previous versions, the file will be cached by VS until the solution is closed.
来源:https://stackoverflow.com/questions/44423582/link-additional-files-in-visual-studio