在使用 dotnet 构建的时候提示 error : SourceRoot items must include at least one top-level (not nested) item when DeterministicSourcePaths is true 构建失败

我在库里使用了 SourceLink 这个库,用来关联代码

此时在构建时候有如下提示

C:\Users\runneradmin\AppData\Local\Microsoft\dotnet\sdk\3.1.300\Roslyn\Microsoft.Managed.Core.targets(104,5): error : SourceRoot items must include at least one top-level (not nested) item when DeterministicSourcePaths is true [D:\a\dotnetCampus.Ipc\dotnetCampus.Ipc\src\dotnetCampus.Ipc.Abstractions\dotnetCampus.Ipc.Abstractions.csproj]

解决方法就是在 csproj 等定义 SourceRoot 这个属性的值,这个值需要表示当前的源代码的最顶层路径

<ItemGroup>
  <SourceRoot Include="../"/>
</ItemGroup>

下面是整个 csproj 的定义代码,方便大家了解上面代码写在哪

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
        <SourceRoot Include="../"/>
    </ItemGroup>

上面代码使用的是相对的路径,而一个比较好的方法是写在 Directory.Build.props 文件里,关于 Directory.Build.props 文件,请看 Roslyn 使用 Directory.Build.props 文件定义编译

在 Directory.Build.props 文件添加如下代码就可以

<ItemGroup>
  <SourceRoot Include="$(MSBuildThisFileDirectory)/"/>
</ItemGroup>

上面代码的 $(MSBuildThisFileDirectory) 表示的是当前文件所在的文件夹,这是构建时的常量,更多常量请看 项目文件中的已知属性(知道了这些,就不会随便在 csproj 中写死常量啦) - walterlv

本文的解决方法是在 DeterministicSourcePaths can break building if source control information not available · Issue #37379 · dotnet/roslyn 找到的

我搭建了自己的博客 https://blog.lindexi.com/ 欢迎大家访问,里面有很多新的博客。

如果在博客看到有任何不懂的,欢迎交流