Marko
Marko

Reputation: 13233

How can I get to the root folder of another project in a .NET Core solution?

I need to read the settings file (appsettings.json) from another project in my solution. When I use:

Directory.GetCurrentDirectory()

From within the current project, I get the following path:

{projectRootFolder}\bin\Debug\netcoreapp3.0\

My question is: How can I get to the exact same folder in another project in the same solution? Or is there a better way to access the settings file from another project within the current solution?

Upvotes: 3

Views: 1894

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239290

What you're attempting to do is not possible. There's no inherent way for ASP.NET Core to know where a totally different app running in a totally different process is located.

If you need to access appsettings.json from another project, then you would need to include it as a linked file in your project, and set it to copy to output. Then, you're accessing it actually from your project (which is all you can do), but the file itself is shared.

However, this is almost always a bad idea, and usually a sign that you're doing something wrong. If you truly do need to share the settings, then what you should be doing is putting them in a distributed config provider like Azure Key Vault or similar, where both projects can independently access the settings from a common store.

Upvotes: 0

Dietatko
Dietatko

Reputation: 382

If I understand the problem correctly there are two misconceptions:

  1. It has little sense to access output directory of an another project as the structure has sense in compile time only. You will not have the same structure in run-time once the application is "published".

  2. The Directory.GetCurrentDirectory() returns the current working directory. It is just a coincidence to be set to project output directory by Visual Studio. It can be totally different directory.

It is not clear to me what exactly you are trying to achieve. I recommend using the configuration system provided by .net core to access the configuration and add that other appsettings.json as another configuration provider.

If you really need to open the settings file then the project with the settings file (A) should mark the file as "Copy to Output Directory" and the project to open the file (B) should reference the project A. So the settings file will be copied to output of the project A too.

Upvotes: 0

Related Questions