Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include files in library in .net core

Tags:

c#

.net

.net-core

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.

like image 640
Eric Avatar asked Oct 18 '25 22:10

Eric


1 Answers

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.

like image 91
eddyP23 Avatar answered Oct 20 '25 11:10

eddyP23



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!