1

We have an ASP NET Core 6 API application hosted on Azure App Service. Together with the application we would like to deploy some external xml files that are used later on by the backend runtime. We have added them to the project and set CopyToOutputDirectory = true.

Have to questions:

  1. How to access these files from code in safe way? What we tried is
  • Assembly.GetExecutingAssembly().GetName().CodeBase)?.Substring(6) to get base path but it looks hacky.
  • _webHostingEnvironment.ContentRootPath but it returns wrong location in development (project root folder instead of /bin)
  • using relative path Path.GetFullName("file.xml") but it returns project root folder in development as well
  1. We saw that there is another property that can be set on file called CopyToPublishDirectory. When it should be set? We set only CopyToOutputDirectory and it seems to work also when doing dotnet publish. Any reference?
GrzegorzM
  • 842
  • 8
  • 19
  • Does this answer your question? [How can I get the application's path in a .NET console application?](https://stackoverflow.com/questions/837488/how-can-i-get-the-applications-path-in-a-net-console-application) – gunr2171 Sep 28 '22 at 11:49
  • When deploying a project the files need to be in same folder as the executable just like they are in the bin folder of the project. So you do not need to use the folder name to access the files. – jdweng Sep 28 '22 at 11:50
  • @gunr2171, no it doesn't. I am asking about ASP NET Core application hosted on azure, your question is about console app. – GrzegorzM Sep 28 '22 at 11:50
  • I'm not sure how "being on Azure" makes a difference. Why the Substring(6)? If you're setting the Working Directory (or it's already set the the application's binaries directory), then a relative path can work as jdweng said. – gunr2171 Sep 28 '22 at 11:51
  • @gunr2171 when using relative path, it doesn't work locally (in development). Path.GetFullPath("file.xml") returns project root folder locally instead of /bin where files are copied to. – GrzegorzM Sep 28 '22 at 12:02

1 Answers1

0

Let's approach this problem in a different way. When we publish the project, we include the bin folder in the publish file. Then you can access .xml inside the bin folder.

  1. Show all files and include to your project.

    show all file

    Include bin folder

  2. Open .csproj file and modify it.

    Include bin folder

    And your csproj file should be like:

    https://dotnetfiddle.net/qG3W8h

    comment out this paragraph and add CopyToOutputDirectory, like below:

    https://dotnetfiddle.net/jrccnJ

  3. Then you can deploy it, then you can find the bin folder.

    Include bin folder

  4. Then you can access the file gracefully.

Jason Pan
  • 15,263
  • 1
  • 14
  • 29