Asp.Net Core 获取应用程序相关目录

news/2024/9/25 22:27:40

原文链接:https://blog.csdn.net/hefeng_aspnet/article/details/135859719

在ASP.NET Core中,可以通过以下三种方式获取应用程序所在目录:

1、使用`AppContext.BaseDirectory`属性:
   string appDirectory = AppContext.BaseDirectory;

例如:D:\后端项目\testCore\test.WebApi\bin\Debug\net6.0\

2、使用`IHostEnvironment`服务: 在ASP.NET Core的启动文件(如Program.cs)中,可以通过依赖注入获取`IHostEnvironment`服务,并使用其`ContentRootPath`属性来获取应用程序所在目录:
   string appDirectory = hostEnvironment.ContentRootPath;

例如:D:\后端项目\testCore\test.WebApi\wwwroot

3、使用`IHostingEnvironment`服务: 在较早版本的ASP.NET Core中,可以使用`IHostingEnvironment`服务获取应用程序所在目录。方法与上述相似:
   string appDirectory = hostingEnvironment.ContentRootPath;

例如:D:\后端项目\testCore\test.WebApi\wwwroot

4、使用程序集信息获取typeof(Program)方式:

var executablePath = Assembly.GetEntryAssembly().Location;

string basePath2 =Path.GetDirectoryName(typeof(Program).Assembly.Location);

例如:D:\后端项目\testCore\test.WebApi\bin\Debug\net6.0\

5.依赖注入:

using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

public class Startup
{
    private readonly IHostEnvironment _hostEnvironment;

    public Startup(IHostEnvironment hostEnvironment)
    {
        _hostEnvironment = hostEnvironment;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // 添加其他服务

        string appDirectory = _hostEnvironment.ContentRootPath;

        // 使用 appDirectory 进行其他操作
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // 配置中间件

        app.Run(async (context) =>
        {
            string appDirectory = env.ContentRootPath;

            await context.Response.WriteAsync($"Application Directory: {appDirectory}");
        });
    }
}

上面代码属NetCore早期版本,.NetCore3.1 后:

创建项目:

Startup中Configure自动注入IWebHostEnvironment:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Controller中直接注入即可:

private IWebHostEnvironment _evn;

public FileUploadController(IWebHostEnvironment evn)
{
    this._evn = evn;
}

使用:string webroot = _evn.WebRootPath;//拿到 wwwroot 路径

6、创建类方式:

1.先创建一个类:
public static class MyServiceProvider
    {
        public static IServiceProvider ServiceProvider
        {
            get; set;
        }
    }
2.Startup.cs中Configure方法中添加 :   

MyServiceProvider.ServiceProvider = app.ApplicationServices;

3.在需要用到程序路径的地方,引用:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
string path = MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>().ContentRootPath;  //.NET Core 3.1,IHostingEnvironment 要改为IHostEnvironment

 效果如下:

 

获取了路径:D:\\Project\\MyWebsite\\UI

4.如果需要获取UI下的wwwroot

路径方法得改一下,为
    static string path = MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>().WebRootPath;  //.NET Core 3.1,IHostingEnvironment 要改为IHostEnvironment

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/46131.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

索引创建规则及优化

示例: drop table if exists emp; create table emp (eid int CLUSTER primary key identity(1,1),ename varchar(200),age int,hiredate date,sal int,deptno int); declare i int; begin for i in 1..50000 loop insert into emp (ename,age,hiredate,sal,deptno) select d…

[模式识别复习笔记] 第6章 PCA

1. 主成分分析 PCA PCA:寻找最能够 表示 原始数据的投 影方法,对数据进行降维,除去冗余的信息。——不考虑类别 1.1 PCA 主要步骤计算 散布矩阵 \(S\)(或者样本的协方差矩阵) \[S = \sum_{i=1}^{n}(\bm{x}_i - \bm{\mu})(\bm{x}_i - \bm{\mu})^{\text{T}} \]其中 \(\bm{\m…

一个练习项目,好玩的bbs-前端部分

common.jsfunction setCookie(name, value, daysToLive = 7) {let cookie = name + "=" + encodeURIComponent(value);if (typeof daysToLive === "number") {cookie += "; max-age=" + (daysToLive*24*60*60); // max-age单位是秒}document.coo…

Python版WGCNA分析和蛋白质相互作用PPI分析教程

在前面的教程中,我们介绍了使用omicverse完成基本的RNA-seq的分析流程,在本节教程中,我们将介绍如何使用omicverse完成加权基因共表达网络分析WGCNA以及蛋白质相互作用PPI分析。环境的下载 在这里我们只需要安装omicverse环境即可,有两个方法:一个是使用conda:conda inst…

一个练习项目,好玩的bbs-c#

c#代码:using MySql.Data.MySqlClient; using System.Data; using Newtonsoft.Json; using System.Security.Cryptography; using System.Text;int pagesize = 20; string secretKey = "saacac3423@21212";var builder = WebApplication.CreateSlimBuilder(args); v…

一个练习项目,好玩的bbs-java

java这个我是用springboot做的 目录结构 application.ymlspring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/my_bbs?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8&allowPubl…

从 Docker Hub 拉取镜像受阻?这些解决方案帮你轻松应对

最近一段时间 Docker 镜像一直是 Pull 不下来的状态,感觉除了挂🪜,想直连 Docker Hub 是几乎不可能的。更糟糕的是,很多原本可靠的国内镜像站,例如一些大厂和高校运营的,也陆续关停了,这对我们这些个人开发者和中小企业来说是挺难受的。之前,通过这些镜像站,我们可以…

redis自学(47)服务端优化

持久化配置 Redis的持久化虽然可以保证数据安全,但也会带来很多额外的开销,因此持久化请遵循下列建议: ① 用来做缓存的redis实例尽量不要开启持久化功能 ② 建议关闭RDB持久化功能,使用AOF持久化(RDB的数据安全性一直是有问题的,两次RDB的时间比较长,又不能频繁的RDB…