简体   繁体   中英

Copying resources on build in ASP.NET Core

In my project I have a resource file named devices.json that I maintain outside of the project to ensure consistency between different projects. So I only have the file added as a link with:

<ItemGroup>
    <Content Include="..\..\resources\devices.json" Link="devices.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
</ItemGroup>

The file gets copied to the build folder correctly but asp.net core projects seem to run with the project root directory set as the Working Dir. So if I try to read the file with File.ReadAllText("devices.json") it will throw a FileNotFound exception.

Is there a way to copy the devices.json file to the project root dir on build so it will be accessible without hardcoding paths to the dev output dir?

Id rather avoid having to write string text;

if(env.IsDevelopment())
{
  text = File.ReadAllText("bin\\Debug\\netcoreapp2.1\\devices.json");
}
else
{
  text = File.ReadAllText("bin\\Release\\netcoreapp2.1\\devices.json");
}

And even if I did, this will break as soon as i publish the project since then the entire project will be copied to the Publish dir which will then run as the CurrentWorking dir.

Any sugestions on how to solve this?

You can use a build target in your project file to copy it across:

  <Target Name="copyDevices" AfterTargets="AfterBuild">
    <Copy SourceFiles="../../resources/devices.json" DestinationFolder="$(OutDir)" />
  </Target>

Then use the following to read the file within your web app:

            var test = File.ReadAllText(
    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "devices.json")
);

在此处输入图片说明

text = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "devices.json"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM