What is environment path when call method in referenced project?

Viewed 46

There two project in a solution which one of them is referenced another. Project 1: .NET Core MVC Project 2: .NET Core API

Both projects are docker enabled with Linux as OS.

Project 2 has Project 1 as referenced project.

A method for saving file on server is in Project 1, it is used for saving file in wwwroot/folder.

An API is in Project 2 for to be consumed outside.

When I call the API, referenced method will be called but the path for saving file raised an exception like as below:

Could not find a part of the path '/app/D:\dev\Project1\wwwroot\folder

Saving file method:

    StringBuilder xmlFilePath = new StringBuilder();

    using (var ms = new MemoryStream())
    using (var writer = XmlWriter.Create(ms, settings))
    {
        doc.Save(writer);
        var xmlString = Encoding.UTF8.GetString(ms.ToArray());

        var pathFolder = _configuration.GetSection("FilesUrl").Value;

        xmlFilePath.Append(
            Path.Combine(pathFolder, 
                         model.Domain.ToLower().Trim() + "-" + model.LanguageCode.ToLower().Trim() + "-file.xml"));
        using (var w = File.CreateText(xmlFilePath.ToString()))
        {
            await w.WriteLineAsync(xmlString);
        }
    }

Edit: I found that when project is running under Docker, Directory.GetCurrentDirectory() will set as /app, but changing project running under Kestrel or IIS will make it as common windows directory path.

enter image description here

What is wrong in my code? Why generated path contains "/app/"?

1 Answers

The codes you showed seems have no relationship with Directory.GetCurrentDirectory(),And For your requirement,you could try with IWebHostEnviroment.WebRootPath.

the WebrootPath of your webapi project could be setted as below in .net 6:

var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ ContentRootPath=@"......"   WebRootPath = "....");
Related