4

I have Project A which depends on Project B.

In Project B I am including additional files in the build out like this:

<ItemGroup>
    <None Include="jsfiles/**/*"  CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

In Project B, I'm loading the files like this:

File.ReadAllText("jsfiles/foo.js");

This copies the files successfully into the out directory. But when I include Project B in Project A, the runtime is resolving files relative to the root of Project A and not the output directory. Because the files don't exist in Project A's root (but they do exist in Project A's output dir), they aren't found.

What's the proper way to load the files in Project B so that it still work when Project B is included in Project A?

Basically, I'm just looking for the right way to include additional resources in a project.

1
  • Did u manage to find a solution? We are facing a similar problem :/ Commented Sep 29, 2020 at 15:22

2 Answers 2

2

Our solution hierarchy:

ProjectA
  Startup.cs       // Uses TextService.cs that uses Text.txt
  ProjectA.csproj  // Does not want to now anything about how TextService works
                   // just has a dependency on Project B
ProjectB
  Text.txt
  TextService.cs   // This one uses Text.txt file
  ProjectB.csproj  // Contains EmbeddedResource with Text.txt here

Your use case might differ, but what I found worked for us is using EmbeddedResource instead of Content tag in the csproj file. This way, the file gets included in both of the above cases:

  • when building ProjectB
  • When Publishing ProjectA (that has a ProjectB dependency)

The code block in the ProjectB.csproj:

<ItemGroup>
  <EmbeddedResource Include="path\to\Text.txt">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </EmbeddedResource>
</ItemGroup>

Alternatively, this can be done in Visual Studio (tested on 2019) by going to Properties of the txt file and setting Build Action: Embedded resource.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use linking. You'll need to add link in Project A to the file in Project B:

<ItemGroup>  
  <Content Include="..\Project B\jsfiles\foo.js" Link="jsfiles\foo.js" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>  

Though you have to create a link to each file in your folder with this approach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.