Visual studio 2017 : nesting files in a class libr

2020-03-24 08:38发布

问题:

In web projects you have the option of nesting files

 + startup.cs
   +--startup.internals.cs
   +--startup.configuration.cs

Is there any way to achieve the same behavior in a class library project as well ?

Updates : Partially solved

Ok got it ,

You need to be aware of your files path.

for a structure like this (the files are at project level)

+-- myProject.csproj
   +-- startup.cs
   +-- startup.internals.cs
   +-- startup.configuration.cs

Then this is the configuration you are looking for.

  <ItemGroup>
    <Compile Update="startup.*.cs">
      <DependentUpon>startup.cs</DependentUpon>
    </Compile>
  </ItemGroup>

For a nested folder structure

+-- myProject.csproject
   +-- Folder_A
      +-- Folder_A1
         +-- startup.cs
         +-- startup.internals.cs
         +-- startup.configuration.cs

you need to get hold of the project path using the buildin $(ProjectDir) macro

  <ItemGroup>
    <Compile Update=" $(ProjectDir)\Folder_A\Folder_A1\startup.*.cs">
      <DependentUpon> $(ProjectDir)\Folder_A\Folder_A1\startup.cs</DependentUpon>
    </Compile>
  </ItemGroup>

Why do I say it is partially working, well because if I exit Visual and then open it again, for the 2nd type of structure, it will un-nest the files.

Some help anyone ?

回答1:

To answer your Updates : Partially solved:

Something similar to this issue. DependentUpon is the correct element to use to achieve the nesting that you want.

But, your value cannot be expression that includes wildcards. It must be a single file that is under the same folder or a sub-folder. If your file exists in a sub-folder, you must specify the file via a relative path. So the content of your ItemGroup should be like this:

<Compile Include="Folder_A\Folder_A1\startup.cs" />
<Compile Include="Folder_A\Folder_A1\startup.configuration.cs">
  <DependentUpon>startup.cs</DependentUpon>
</Compile>
<Compile Include="Folder_A\Folder_A1\startup.internals.cs">
  <DependentUpon>startup.cs</DependentUpon>
</Compile>

And after my check, I think you need to use the Include attribute instead of Update if you are building a .NET FX class library project.

Update: The Update attribute is available only for .NET Core projects according to this doc.

And if in a .NET Core project, like what you indicated in a comment, maybe Update is more suitable:

<Compile Update="Folder_A\Folder_A1\startup.internals.cs">
  <DependentUpon>startup.cs</DependentUpon>
</Compile>


回答2:

I believe you can do this in your csproj file.

<Compile Include="startup.cs">
    <DependentUpon>startup.internals.xaml</DependentUpon>
    <DependentUpon>startup.configureation.xaml</DependentUpon>
</Compile>