简体   繁体   中英

How can I get the root of my project in ASP.NET and not the location of IIS Express using .CurrentDirectory()?

I have an ASP.NET Core project that I'm developing and I'm making use of LiteDB as a database solution. In order to instantiate my database I need to provide a URI so that the program knows where to create the database.

Usually I'd do something like System.Environment.CurrentDirectory() to find the current directory I'm in and modify that, however the result of this command turns out to be C:\\program files\\IIS Express or something similar. Basically the current directory points to the location of IIS Express.

Instead I want to get the root of my ASP.NET project, the location that contains my controllers folder, appsettings.json, bin and obj folders.

What command do I need to use to get a string representing this location? I don't want to use a hard coded string for obvious reasons.

If you don't have access to DI you could try:

Assembly.GetExecutingAssembly().Location

If you have access to DI, try this:

Inject the IHostingEnvironment and call environment.ContentRootPath

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

You may be better served by using a dedicated location (such as a network share) rather than the folder that contains the executable code. Having user data mixed into deployed code comes with a lot of headaches:

  • Deployments become more complex as they need to account for the presence of user data. This is especially true if you need to delete pre-existing code during a deployment.
  • If the user data is sensitive, developers may be denied access to read the deployed code. This can make troubleshooting issues much harder.
  • Backups of deployed code will contain user data, which means they will always appear to be different even if nothing (code-wise) has changed.

Of course, this all assumes that the production environment is configured differently from developers' local machines.

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