alaa_sayegh
alaa_sayegh

Reputation: 2211

ASP.Net WebApi netcore 2.2 access local file

I read somewhere that .NetCore 2.2 has a bug in GetCurrentDirectory method. https://github.com/aspnet/AspNetCore/issues/4206

We have an ASP.Net WebApi with netcore 2.2.

I was wondering, what is the best way to access a local file which is located in my root directory.

There are too many examples but am looking for the best practise that will work locally and on production (docker container). Currently i use this syntax:

var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string csvPath = Path.Combine(baseDirectory, fileName);

The csv file will be always copied to the output directory and once published it will be in the same folder as the executables.

Other syntax like: Injecting the IHostingEnvironment in the service and then call the ContentRootPath. like this:

private readonly IHostingEnvironment _hostingEnvironment;

public Service(IHostingEnvironment hostingEnvironment)
{
  _hostingEnvironment = hostingEnvironment;
}

string csvPath = Path.Combine(_hostingEnvironment.ContentRootPath, fileName);

Upvotes: 1

Views: 2354

Answers (1)

100mil
100mil

Reputation: 114

There is one way, that is worked for me with .Net core 2.2.

you can access the file in your .Net application using following line.

 string path = Path.Combine(Directory.GetCurrentDirectory),filename);

And copy your file inside the docker container while building image.

COPY --from=build /app/ .
COPY --from=build /app/[folder-where-file]/ .

Upvotes: 2

Related Questions