当前位置: 首页 > news >正文

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

在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.lryc.cn/news/290221.html

相关文章:

  • 文献速递:人工智能医学影像分割--- 深度学习分割骨盆骨骼:大规模CT数据集和基线模型
  • PaddleNLP的简单使用
  • 2. MySQL 多实例
  • 两个五层决策树和一个十层决策树的区别
  • 案例分析技巧-软件工程
  • 如何使用docker compose安装APITable并远程访问登录界面
  • 深入了解Matplotlib中的子图创建方法
  • 云计算运维 · 第三阶段 · git
  • 【幻兽帕鲁】开服务器,高性能高带宽(100mbps),免费!!!【学生党强推】
  • 微信小程序|推箱子小游戏
  • 【Linux】—— 信号的产生
  • 【算法】Hash 算法-关注优化细节
  • 回归预测 | Matlab实现CPO-SVR冠豪猪优化支持向量机的数据多输入单输出回归预测
  • Idea设置代理后无法clone git项目
  • tkMapper 通用mapper的批量更新 批量新增 官方实现 springboot项目 依赖引入
  • 【leetcode刷刷】回溯:77.组合
  • 【OOP】Python的OOP编程笔记
  • 一进一出模拟量信号隔离变送器
  • Mybatis-plus原生pages分页未生效的解决方案
  • 【linux】-centos7版本前后-变化篇
  • 001集—shapefile(.shp)格式详解——arcgis
  • ssrf服务器请求伪造漏洞(个人学习)
  • 【前端web入门第二天】03 表单-下拉菜单 文本域 label标签 按钮 【附注册信息综合案例】
  • 回响科技二面面试题解答
  • node学习过程中的终端命令
  • oracle版本号中的i,G,C代表什么含义
  • Unity2D_角色移动跳跃
  • 23-GPTs Actions详细解析:如何查找、对接API,及如何编写Schema
  • 微信小程序canvas画布实现椭圆元素自由缩放、移动功能
  • 使用Excel计算--任务完成总工作日时长