在Visual Studio中链接其他文件 [英] Link Additional Files in Visual Studio
问题描述
我试图在我的Visual Studio 2017的C#项目中包含stylecop.json。我想出了如何通过在任何文本编辑器中修改.csproj来做到这一点的方法。
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.
推荐答案
您可以在解决方案目录中的某个位置添加一个 Directory.Build.targets
文件(将应用于该目录或该目录下的所有项目),其内容如下:
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>
请注意,在此处使用%(Identity)
对于项目锥之外的项目不是最佳选择-例如当您拥有< AdditionalFiles Include = .. \..\foo.bar />
时。为此,您可以使用类似于VS中基于SDK的项目的机制2017 15.3 / .net core 2.0工具:
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>
这甚至会保留与例如匹配的项目的目录层次结构 .. \shared\ ** \ * .json
和目标文件夹可以使用 LinkBase
进行设置元数据:
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>
请注意,对<$ c $进行更改后,您可能需要关闭并重新打开解决方案c> Directory.Build.targets 。在即将到来的VS 2017 15.3更新中,VS将自动监视更改。在以前的版本中,文件将由VS缓存,直到解决方案关闭。
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.
这篇关于在Visual Studio中链接其他文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!